1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
13 #include "statements.h"
14 #include "expressions.h"
24 Gogo::Gogo(Backend* backend, Linemap* linemap, int int_type_size,
30 globals_(new Bindings(NULL)),
32 imported_unsafe_(false),
43 pkgpath_from_option_(false),
44 prefix_from_option_(false),
47 specific_type_functions_(),
48 specific_type_functions_are_written_(false),
49 named_types_are_converted_(false)
51 const Location loc = Linemap::predeclared_location();
53 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
54 RUNTIME_TYPE_KIND_UINT8);
55 this->add_named_type(uint8_type);
56 this->add_named_type(Type::make_integer_type("uint16", true, 16,
57 RUNTIME_TYPE_KIND_UINT16));
58 this->add_named_type(Type::make_integer_type("uint32", true, 32,
59 RUNTIME_TYPE_KIND_UINT32));
60 this->add_named_type(Type::make_integer_type("uint64", true, 64,
61 RUNTIME_TYPE_KIND_UINT64));
63 this->add_named_type(Type::make_integer_type("int8", false, 8,
64 RUNTIME_TYPE_KIND_INT8));
65 this->add_named_type(Type::make_integer_type("int16", false, 16,
66 RUNTIME_TYPE_KIND_INT16));
67 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
68 RUNTIME_TYPE_KIND_INT32);
69 this->add_named_type(int32_type);
70 this->add_named_type(Type::make_integer_type("int64", false, 64,
71 RUNTIME_TYPE_KIND_INT64));
73 this->add_named_type(Type::make_float_type("float32", 32,
74 RUNTIME_TYPE_KIND_FLOAT32));
75 this->add_named_type(Type::make_float_type("float64", 64,
76 RUNTIME_TYPE_KIND_FLOAT64));
78 this->add_named_type(Type::make_complex_type("complex64", 64,
79 RUNTIME_TYPE_KIND_COMPLEX64));
80 this->add_named_type(Type::make_complex_type("complex128", 128,
81 RUNTIME_TYPE_KIND_COMPLEX128));
83 if (int_type_size < 32)
85 this->add_named_type(Type::make_integer_type("uint", true,
87 RUNTIME_TYPE_KIND_UINT));
88 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
89 RUNTIME_TYPE_KIND_INT);
90 this->add_named_type(int_type);
92 this->add_named_type(Type::make_integer_type("uintptr", true,
94 RUNTIME_TYPE_KIND_UINTPTR));
96 // "byte" is an alias for "uint8".
97 uint8_type->integer_type()->set_is_byte();
98 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
100 this->add_named_type(byte_type->type_value());
102 // "rune" is an alias for "int32".
103 int32_type->integer_type()->set_is_rune();
104 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
106 this->add_named_type(rune_type->type_value());
108 this->add_named_type(Type::make_named_bool_type());
110 this->add_named_type(Type::make_named_string_type());
112 // "error" is interface { Error() string }.
114 Typed_identifier_list *methods = new Typed_identifier_list;
115 Typed_identifier_list *results = new Typed_identifier_list;
116 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
117 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
118 methods->push_back(Typed_identifier("Error", method_type, loc));
119 Interface_type *error_iface = Type::make_interface_type(methods, loc);
120 error_iface->finalize_methods();
121 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
122 this->add_named_type(error_type);
125 this->globals_->add_constant(Typed_identifier("true",
126 Type::make_boolean_type(),
129 Expression::make_boolean(true, loc),
131 this->globals_->add_constant(Typed_identifier("false",
132 Type::make_boolean_type(),
135 Expression::make_boolean(false, loc),
138 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
141 Expression::make_nil(loc),
144 Type* abstract_int_type = Type::make_abstract_integer_type();
145 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
148 Expression::make_iota(),
151 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
152 new_type->set_is_varargs();
153 new_type->set_is_builtin();
154 this->globals_->add_function_declaration("new", NULL, new_type, loc);
156 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
157 make_type->set_is_varargs();
158 make_type->set_is_builtin();
159 this->globals_->add_function_declaration("make", NULL, make_type, loc);
161 Typed_identifier_list* len_result = new Typed_identifier_list();
162 len_result->push_back(Typed_identifier("", int_type, loc));
163 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
165 len_type->set_is_builtin();
166 this->globals_->add_function_declaration("len", NULL, len_type, loc);
168 Typed_identifier_list* cap_result = new Typed_identifier_list();
169 cap_result->push_back(Typed_identifier("", int_type, loc));
170 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
172 cap_type->set_is_builtin();
173 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
175 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
176 print_type->set_is_varargs();
177 print_type->set_is_builtin();
178 this->globals_->add_function_declaration("print", NULL, print_type, loc);
180 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
181 print_type->set_is_varargs();
182 print_type->set_is_builtin();
183 this->globals_->add_function_declaration("println", NULL, print_type, loc);
185 Type *empty = Type::make_empty_interface_type(loc);
186 Typed_identifier_list* panic_parms = new Typed_identifier_list();
187 panic_parms->push_back(Typed_identifier("e", empty, loc));
188 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
190 panic_type->set_is_builtin();
191 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
193 Typed_identifier_list* recover_result = new Typed_identifier_list();
194 recover_result->push_back(Typed_identifier("", empty, loc));
195 Function_type* recover_type = Type::make_function_type(NULL, NULL,
198 recover_type->set_is_builtin();
199 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
201 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
202 close_type->set_is_varargs();
203 close_type->set_is_builtin();
204 this->globals_->add_function_declaration("close", NULL, close_type, loc);
206 Typed_identifier_list* copy_result = new Typed_identifier_list();
207 copy_result->push_back(Typed_identifier("", int_type, loc));
208 Function_type* copy_type = Type::make_function_type(NULL, NULL,
210 copy_type->set_is_varargs();
211 copy_type->set_is_builtin();
212 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
214 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
215 append_type->set_is_varargs();
216 append_type->set_is_builtin();
217 this->globals_->add_function_declaration("append", NULL, append_type, loc);
219 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
220 complex_type->set_is_varargs();
221 complex_type->set_is_builtin();
222 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
224 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
225 real_type->set_is_varargs();
226 real_type->set_is_builtin();
227 this->globals_->add_function_declaration("real", NULL, real_type, loc);
229 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
230 imag_type->set_is_varargs();
231 imag_type->set_is_builtin();
232 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
234 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
235 delete_type->set_is_varargs();
236 delete_type->set_is_builtin();
237 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
240 // Convert a pkgpath into a string suitable for a symbol. Note that
241 // this transformation is convenient but imperfect. A -fgo-pkgpath
242 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
243 // possibly leading to link time errors.
246 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
248 std::string s = pkgpath;
249 for (size_t i = 0; i < s.length(); ++i)
252 if ((c >= 'a' && c <= 'z')
253 || (c >= 'A' && c <= 'Z')
254 || (c >= '0' && c <= '9')
265 // Get the package path to use for type reflection data. This should
266 // ideally be unique across the entire link.
269 Gogo::pkgpath() const
271 go_assert(this->pkgpath_set_);
272 return this->pkgpath_;
275 // Set the package path from the -fgo-pkgpath command line option.
278 Gogo::set_pkgpath(const std::string& arg)
280 go_assert(!this->pkgpath_set_);
281 this->pkgpath_ = arg;
282 this->pkgpath_set_ = true;
283 this->pkgpath_from_option_ = true;
286 // Get the package path to use for symbol names.
289 Gogo::pkgpath_symbol() const
291 go_assert(this->pkgpath_set_);
292 return this->pkgpath_symbol_;
295 // Set the unique prefix to use to determine the package path, from
296 // the -fgo-prefix command line option.
299 Gogo::set_prefix(const std::string& arg)
301 go_assert(!this->prefix_from_option_);
303 this->prefix_from_option_ = true;
306 // Munge name for use in an error message.
309 Gogo::message_name(const std::string& name)
311 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
314 // Get the package name.
317 Gogo::package_name() const
319 go_assert(this->package_ != NULL);
320 return this->package_->package_name();
323 // Set the package name.
326 Gogo::set_package_name(const std::string& package_name,
329 if (this->package_ != NULL)
331 if (this->package_->package_name() != package_name)
332 error_at(location, "expected package %<%s%>",
333 Gogo::message_name(this->package_->package_name()).c_str());
337 // Now that we know the name of the package we are compiling, set
338 // the package path to use for reflect.Type.PkgPath and global
340 if (!this->pkgpath_set_)
342 if (!this->prefix_from_option_)
343 this->prefix_ = "go";
344 this->pkgpath_ = this->prefix_ + '.' + package_name;
345 this->pkgpath_set_ = true;
348 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
350 this->package_ = this->register_package(this->pkgpath_, location);
351 this->package_->set_package_name(package_name, location);
353 if (this->is_main_package())
355 // Declare "main" as a function which takes no parameters and
357 Location uloc = Linemap::unknown_location();
358 this->declare_function("main",
359 Type::make_function_type (NULL, NULL, NULL, uloc),
364 // Return whether this is the "main" package. This is not true if
365 // -fgo-pkgpath or -fgo-prefix was used.
368 Gogo::is_main_package() const
370 return (this->package_name() == "main"
371 && !this->pkgpath_from_option_
372 && !this->prefix_from_option_);
378 Gogo::import_package(const std::string& filename,
379 const std::string& local_name,
380 bool is_local_name_exported,
383 if (filename == "unsafe")
385 this->import_unsafe(local_name, is_local_name_exported, location);
389 Imports::const_iterator p = this->imports_.find(filename);
390 if (p != this->imports_.end())
392 Package* package = p->second;
393 package->set_location(location);
394 package->set_is_imported();
395 std::string ln = local_name;
396 bool is_ln_exported = is_local_name_exported;
399 ln = package->package_name();
400 go_assert(!ln.empty());
401 is_ln_exported = Lex::is_exported_name(ln);
405 Bindings* bindings = package->bindings();
406 for (Bindings::const_declarations_iterator p =
407 bindings->begin_declarations();
408 p != bindings->end_declarations();
410 this->add_named_object(p->second);
413 package->set_uses_sink_alias();
416 ln = this->pack_hidden_name(ln, is_ln_exported);
417 this->package_->bindings()->add_package(ln, package);
422 Import::Stream* stream = Import::open_package(filename, location);
425 error_at(location, "import file %qs not found", filename.c_str());
429 Import imp(stream, location);
430 imp.register_builtin_types(this);
431 Package* package = imp.import(this, local_name, is_local_name_exported);
434 if (package->pkgpath() == this->pkgpath())
436 ("imported package uses same package path as package "
437 "being compiled (see -fgo-pkgpath option)"));
439 this->imports_.insert(std::make_pair(filename, package));
440 package->set_is_imported();
446 // Add an import control function for an imported package to the list.
449 Gogo::add_import_init_fn(const std::string& package_name,
450 const std::string& init_name, int prio)
452 for (std::set<Import_init>::const_iterator p =
453 this->imported_init_fns_.begin();
454 p != this->imported_init_fns_.end();
457 if (p->init_name() == init_name
458 && (p->package_name() != package_name || p->priority() != prio))
460 error("duplicate package initialization name %qs",
461 Gogo::message_name(init_name).c_str());
462 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
463 Gogo::message_name(p->package_name()).c_str(),
465 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
466 Gogo::message_name(package_name).c_str(), prio);
471 this->imported_init_fns_.insert(Import_init(package_name, init_name,
475 // Return whether we are at the global binding level.
478 Gogo::in_global_scope() const
480 return this->functions_.empty();
483 // Return the current binding contour.
486 Gogo::current_bindings()
488 if (!this->functions_.empty())
489 return this->functions_.back().blocks.back()->bindings();
490 else if (this->package_ != NULL)
491 return this->package_->bindings();
493 return this->globals_;
497 Gogo::current_bindings() const
499 if (!this->functions_.empty())
500 return this->functions_.back().blocks.back()->bindings();
501 else if (this->package_ != NULL)
502 return this->package_->bindings();
504 return this->globals_;
507 // Return the current block.
510 Gogo::current_block()
512 if (this->functions_.empty())
515 return this->functions_.back().blocks.back();
518 // Look up a name in the current binding contour. If PFUNCTION is not
519 // NULL, set it to the function in which the name is defined, or NULL
520 // if the name is defined in global scope.
523 Gogo::lookup(const std::string& name, Named_object** pfunction) const
525 if (pfunction != NULL)
528 if (Gogo::is_sink_name(name))
529 return Named_object::make_sink();
531 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
532 p != this->functions_.rend();
535 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
538 if (pfunction != NULL)
539 *pfunction = p->function;
544 if (this->package_ != NULL)
546 Named_object* ret = this->package_->bindings()->lookup(name);
549 if (ret->package() != NULL)
550 ret->package()->set_used();
555 // We do not look in the global namespace. If we did, the global
556 // namespace would effectively hide names which were defined in
557 // package scope which we have not yet seen. Instead,
558 // define_global_names is called after parsing is over to connect
559 // undefined names at package scope with names defined at global
565 // Look up a name in the current block, without searching enclosing
569 Gogo::lookup_in_block(const std::string& name) const
571 go_assert(!this->functions_.empty());
572 go_assert(!this->functions_.back().blocks.empty());
573 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
576 // Look up a name in the global namespace.
579 Gogo::lookup_global(const char* name) const
581 return this->globals_->lookup(name);
584 // Add an imported package.
587 Gogo::add_imported_package(const std::string& real_name,
588 const std::string& alias_arg,
589 bool is_alias_exported,
590 const std::string& pkgpath,
592 bool* padd_to_globals)
594 Package* ret = this->register_package(pkgpath, location);
595 ret->set_package_name(real_name, location);
597 *padd_to_globals = false;
599 if (alias_arg == ".")
600 *padd_to_globals = true;
601 else if (alias_arg == "_")
602 ret->set_uses_sink_alias();
605 std::string alias = alias_arg;
609 is_alias_exported = Lex::is_exported_name(alias);
611 alias = this->pack_hidden_name(alias, is_alias_exported);
612 Named_object* no = this->package_->bindings()->add_package(alias, ret);
613 if (!no->is_package())
620 // Register a package. This package may or may not be imported. This
621 // returns the Package structure for the package, creating if it
622 // necessary. LOCATION is the location of the import statement that
623 // led us to see this package.
626 Gogo::register_package(const std::string& pkgpath, Location location)
628 Package* package = NULL;
629 std::pair<Packages::iterator, bool> ins =
630 this->packages_.insert(std::make_pair(pkgpath, package));
633 // We have seen this package name before.
634 package = ins.first->second;
635 go_assert(package != NULL && package->pkgpath() == pkgpath);
636 if (Linemap::is_unknown_location(package->location()))
637 package->set_location(location);
641 // First time we have seen this package name.
642 package = new Package(pkgpath, location);
643 go_assert(ins.first->second == NULL);
644 ins.first->second = package;
650 // Start compiling a function.
653 Gogo::start_function(const std::string& name, Function_type* type,
654 bool add_method_to_type, Location location)
656 bool at_top_level = this->functions_.empty();
658 Block* block = new Block(NULL, location);
660 Function* enclosing = (at_top_level
662 : this->functions_.back().function->func_value());
664 Function* function = new Function(type, enclosing, block, location);
666 if (type->is_method())
668 const Typed_identifier* receiver = type->receiver();
669 Variable* this_param = new Variable(receiver->type(), NULL, false,
670 true, true, location);
671 std::string rname = receiver->name();
672 if (rname.empty() || Gogo::is_sink_name(rname))
674 // We need to give receivers a name since they wind up in
675 // DECL_ARGUMENTS. FIXME.
676 static unsigned int count;
678 snprintf(buf, sizeof buf, "r.%u", count);
682 block->bindings()->add_variable(rname, NULL, this_param);
685 const Typed_identifier_list* parameters = type->parameters();
686 bool is_varargs = type->is_varargs();
687 if (parameters != NULL)
689 for (Typed_identifier_list::const_iterator p = parameters->begin();
690 p != parameters->end();
693 Variable* param = new Variable(p->type(), NULL, false, true, false,
695 if (is_varargs && p + 1 == parameters->end())
696 param->set_is_varargs_parameter();
698 std::string pname = p->name();
699 if (pname.empty() || Gogo::is_sink_name(pname))
701 // We need to give parameters a name since they wind up
702 // in DECL_ARGUMENTS. FIXME.
703 static unsigned int count;
705 snprintf(buf, sizeof buf, "p.%u", count);
709 block->bindings()->add_variable(pname, NULL, param);
713 function->create_result_variables(this);
715 const std::string* pname;
716 std::string nested_name;
717 bool is_init = false;
718 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
720 if ((type->parameters() != NULL && !type->parameters()->empty())
721 || (type->results() != NULL && !type->results()->empty()))
723 "func init must have no arguments and no return values");
724 // There can be multiple "init" functions, so give them each a
726 static int init_count;
728 snprintf(buf, sizeof buf, ".$init%d", init_count);
731 pname = &nested_name;
734 else if (!name.empty())
738 // Invent a name for a nested function.
739 static int nested_count;
741 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
744 pname = &nested_name;
748 if (Gogo::is_sink_name(*pname))
750 static int sink_count;
752 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
754 ret = Named_object::make_function(buf, NULL, function);
756 else if (!type->is_method())
758 ret = this->package_->bindings()->add_function(*pname, NULL, function);
759 if (!ret->is_function() || ret->func_value() != function)
761 // Redefinition error. Invent a name to avoid knockon
763 static int redefinition_count;
765 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
766 ++redefinition_count;
767 ret = this->package_->bindings()->add_function(buf, NULL, function);
772 if (!add_method_to_type)
773 ret = Named_object::make_function(name, NULL, function);
776 go_assert(at_top_level);
777 Type* rtype = type->receiver()->type();
779 // We want to look through the pointer created by the
780 // parser, without getting an error if the type is not yet
782 if (rtype->classification() == Type::TYPE_POINTER)
783 rtype = rtype->points_to();
785 if (rtype->is_error_type())
786 ret = Named_object::make_function(name, NULL, function);
787 else if (rtype->named_type() != NULL)
789 ret = rtype->named_type()->add_method(name, function);
790 if (!ret->is_function())
792 // Redefinition error.
793 ret = Named_object::make_function(name, NULL, function);
796 else if (rtype->forward_declaration_type() != NULL)
798 Named_object* type_no =
799 rtype->forward_declaration_type()->named_object();
800 if (type_no->is_unknown())
802 // If we are seeing methods it really must be a
803 // type. Declare it as such. An alternative would
804 // be to support lists of methods for unknown
805 // expressions. Either way the error messages if
806 // this is not a type are going to get confusing.
807 Named_object* declared =
808 this->declare_package_type(type_no->name(),
809 type_no->location());
811 == type_no->unknown_value()->real_named_object());
813 ret = rtype->forward_declaration_type()->add_method(name,
819 this->package_->bindings()->add_method(ret);
822 this->functions_.resize(this->functions_.size() + 1);
823 Open_function& of(this->functions_.back());
825 of.blocks.push_back(block);
829 this->init_functions_.push_back(ret);
830 this->need_init_fn_ = true;
836 // Finish compiling a function.
839 Gogo::finish_function(Location location)
841 this->finish_block(location);
842 go_assert(this->functions_.back().blocks.empty());
843 this->functions_.pop_back();
846 // Return the current function.
849 Gogo::current_function() const
851 go_assert(!this->functions_.empty());
852 return this->functions_.back().function;
855 // Start a new block.
858 Gogo::start_block(Location location)
860 go_assert(!this->functions_.empty());
861 Block* block = new Block(this->current_block(), location);
862 this->functions_.back().blocks.push_back(block);
868 Gogo::finish_block(Location location)
870 go_assert(!this->functions_.empty());
871 go_assert(!this->functions_.back().blocks.empty());
872 Block* block = this->functions_.back().blocks.back();
873 this->functions_.back().blocks.pop_back();
874 block->set_end_location(location);
878 // Add an erroneous name.
881 Gogo::add_erroneous_name(const std::string& name)
883 return this->package_->bindings()->add_erroneous_name(name);
886 // Add an unknown name.
889 Gogo::add_unknown_name(const std::string& name, Location location)
891 return this->package_->bindings()->add_unknown_name(name, location);
894 // Declare a function.
897 Gogo::declare_function(const std::string& name, Function_type* type,
900 if (!type->is_method())
901 return this->current_bindings()->add_function_declaration(name, NULL, type,
905 // We don't bother to add this to the list of global
907 Type* rtype = type->receiver()->type();
909 // We want to look through the pointer created by the
910 // parser, without getting an error if the type is not yet
912 if (rtype->classification() == Type::TYPE_POINTER)
913 rtype = rtype->points_to();
915 if (rtype->is_error_type())
917 else if (rtype->named_type() != NULL)
918 return rtype->named_type()->add_method_declaration(name, NULL, type,
920 else if (rtype->forward_declaration_type() != NULL)
922 Forward_declaration_type* ftype = rtype->forward_declaration_type();
923 return ftype->add_method_declaration(name, NULL, type, location);
930 // Add a label definition.
933 Gogo::add_label_definition(const std::string& label_name,
936 go_assert(!this->functions_.empty());
937 Function* func = this->functions_.back().function->func_value();
938 Label* label = func->add_label_definition(this, label_name, location);
939 this->add_statement(Statement::make_label_statement(label, location));
943 // Add a label reference.
946 Gogo::add_label_reference(const std::string& label_name,
947 Location location, bool issue_goto_errors)
949 go_assert(!this->functions_.empty());
950 Function* func = this->functions_.back().function->func_value();
951 return func->add_label_reference(this, label_name, location,
955 // Return the current binding state.
958 Gogo::bindings_snapshot(Location location)
960 return new Bindings_snapshot(this->current_block(), location);
966 Gogo::add_statement(Statement* statement)
968 go_assert(!this->functions_.empty()
969 && !this->functions_.back().blocks.empty());
970 this->functions_.back().blocks.back()->add_statement(statement);
976 Gogo::add_block(Block* block, Location location)
978 go_assert(!this->functions_.empty()
979 && !this->functions_.back().blocks.empty());
980 Statement* statement = Statement::make_block_statement(block, location);
981 this->functions_.back().blocks.back()->add_statement(statement);
987 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
990 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
996 Gogo::add_type(const std::string& name, Type* type, Location location)
998 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
1000 if (!this->in_global_scope() && no->is_type())
1001 no->type_value()->set_in_function(this->functions_.back().function);
1004 // Add a named type.
1007 Gogo::add_named_type(Named_type* type)
1009 go_assert(this->in_global_scope());
1010 this->current_bindings()->add_named_type(type);
1016 Gogo::declare_type(const std::string& name, Location location)
1018 Bindings* bindings = this->current_bindings();
1019 Named_object* no = bindings->add_type_declaration(name, NULL, location);
1020 if (!this->in_global_scope() && no->is_type_declaration())
1022 Named_object* f = this->functions_.back().function;
1023 no->type_declaration_value()->set_in_function(f);
1028 // Declare a type at the package level.
1031 Gogo::declare_package_type(const std::string& name, Location location)
1033 return this->package_->bindings()->add_type_declaration(name, NULL, location);
1036 // Declare a function at the package level.
1039 Gogo::declare_package_function(const std::string& name, Function_type* type,
1042 return this->package_->bindings()->add_function_declaration(name, NULL, type,
1046 // Define a type which was already declared.
1049 Gogo::define_type(Named_object* no, Named_type* type)
1051 this->current_bindings()->define_type(no, type);
1057 Gogo::add_variable(const std::string& name, Variable* variable)
1059 Named_object* no = this->current_bindings()->add_variable(name, NULL,
1062 // In a function the middle-end wants to see a DECL_EXPR node.
1064 && no->is_variable()
1065 && !no->var_value()->is_parameter()
1066 && !this->functions_.empty())
1067 this->add_statement(Statement::make_variable_declaration(no));
1072 // Add a sink--a reference to the blank identifier _.
1077 return Named_object::make_sink();
1080 // Add a named object.
1083 Gogo::add_named_object(Named_object* no)
1085 this->current_bindings()->add_named_object(no);
1088 // Mark all local variables used. This is used when some types of
1089 // parse error occur.
1092 Gogo::mark_locals_used()
1094 for (Open_functions::iterator pf = this->functions_.begin();
1095 pf != this->functions_.end();
1098 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
1099 pb != pf->blocks.end();
1101 (*pb)->bindings()->mark_locals_used();
1105 // Record that we've seen an interface type.
1108 Gogo::record_interface_type(Interface_type* itype)
1110 this->interface_types_.push_back(itype);
1113 // Return a name for a thunk object.
1118 static int thunk_count;
1119 char thunk_name[50];
1120 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1125 // Return whether a function is a thunk.
1128 Gogo::is_thunk(const Named_object* no)
1130 return no->name().compare(0, 6, "$thunk") == 0;
1133 // Define the global names. We do this only after parsing all the
1134 // input files, because the program might define the global names
1138 Gogo::define_global_names()
1140 for (Bindings::const_declarations_iterator p =
1141 this->globals_->begin_declarations();
1142 p != this->globals_->end_declarations();
1145 Named_object* global_no = p->second;
1146 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1147 Named_object* no = this->package_->bindings()->lookup(name);
1151 if (no->is_type_declaration())
1153 if (global_no->is_type())
1155 if (no->type_declaration_value()->has_methods())
1156 error_at(no->location(),
1157 "may not define methods for global type");
1158 no->set_type_value(global_no->type_value());
1162 error_at(no->location(), "expected type");
1163 Type* errtype = Type::make_error_type();
1165 Named_object::make_type("erroneous_type", NULL, errtype,
1166 Linemap::predeclared_location());
1167 no->set_type_value(err->type_value());
1170 else if (no->is_unknown())
1171 no->unknown_value()->set_real_named_object(global_no);
1175 // Clear out names in file scope.
1178 Gogo::clear_file_scope()
1180 this->package_->bindings()->clear_file_scope();
1182 // Warn about packages which were imported but not used.
1183 for (Packages::iterator p = this->packages_.begin();
1184 p != this->packages_.end();
1187 Package* package = p->second;
1188 if (package != this->package_
1189 && package->is_imported()
1191 && !package->uses_sink_alias()
1193 error_at(package->location(), "imported and not used: %s",
1194 Gogo::message_name(package->package_name()).c_str());
1195 package->clear_is_imported();
1196 package->clear_uses_sink_alias();
1197 package->clear_used();
1201 // Queue up a type specific function for later writing. These are
1202 // written out in write_specific_type_functions, called after the
1203 // parse tree is lowered.
1206 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1207 const std::string& hash_name,
1208 Function_type* hash_fntype,
1209 const std::string& equal_name,
1210 Function_type* equal_fntype)
1212 go_assert(!this->specific_type_functions_are_written_);
1213 go_assert(!this->in_global_scope());
1214 Specific_type_function* tsf = new Specific_type_function(type, name,
1219 this->specific_type_functions_.push_back(tsf);
1222 // Look for types which need specific hash or equality functions.
1224 class Specific_type_functions : public Traverse
1227 Specific_type_functions(Gogo* gogo)
1228 : Traverse(traverse_types),
1240 Specific_type_functions::type(Type* t)
1242 Named_object* hash_fn;
1243 Named_object* equal_fn;
1244 switch (t->classification())
1246 case Type::TYPE_NAMED:
1248 Named_type* nt = t->named_type();
1249 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1250 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
1252 // If this is a struct type, we don't want to make functions
1253 // for the unnamed struct.
1254 Type* rt = nt->real_type();
1255 if (rt->struct_type() == NULL)
1257 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1258 return TRAVERSE_EXIT;
1262 // If this type is defined in another package, then we don't
1263 // need to worry about the unexported fields.
1264 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
1265 const Struct_field_list* fields = rt->struct_type()->fields();
1266 for (Struct_field_list::const_iterator p = fields->begin();
1270 if (is_defined_elsewhere
1271 && Gogo::is_hidden_name(p->field_name()))
1273 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
1274 return TRAVERSE_EXIT;
1278 return TRAVERSE_SKIP_COMPONENTS;
1281 case Type::TYPE_STRUCT:
1282 case Type::TYPE_ARRAY:
1283 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1284 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1291 return TRAVERSE_CONTINUE;
1294 // Write out type specific functions.
1297 Gogo::write_specific_type_functions()
1299 Specific_type_functions stf(this);
1300 this->traverse(&stf);
1302 while (!this->specific_type_functions_.empty())
1304 Specific_type_function* tsf = this->specific_type_functions_.back();
1305 this->specific_type_functions_.pop_back();
1306 tsf->type->write_specific_type_functions(this, tsf->name,
1313 this->specific_type_functions_are_written_ = true;
1316 // Traverse the tree.
1319 Gogo::traverse(Traverse* traverse)
1321 // Traverse the current package first for consistency. The other
1322 // packages will only contain imported types, constants, and
1324 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1326 for (Packages::const_iterator p = this->packages_.begin();
1327 p != this->packages_.end();
1330 if (p->second != this->package_)
1332 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1338 // Add a type to verify. This is used for types of sink variables, in
1339 // order to give appropriate error messages.
1342 Gogo::add_type_to_verify(Type* type)
1344 this->verify_types_.push_back(type);
1347 // Traversal class used to verify types.
1349 class Verify_types : public Traverse
1353 : Traverse(traverse_types)
1360 // Verify that a type is correct.
1363 Verify_types::type(Type* t)
1366 return TRAVERSE_SKIP_COMPONENTS;
1367 return TRAVERSE_CONTINUE;
1370 // Verify that all types are correct.
1373 Gogo::verify_types()
1375 Verify_types traverse;
1376 this->traverse(&traverse);
1378 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
1379 p != this->verify_types_.end();
1382 this->verify_types_.clear();
1385 // Traversal class used to lower parse tree.
1387 class Lower_parse_tree : public Traverse
1390 Lower_parse_tree(Gogo* gogo, Named_object* function)
1391 : Traverse(traverse_variables
1392 | traverse_constants
1393 | traverse_functions
1394 | traverse_statements
1395 | traverse_expressions),
1396 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1400 set_inserter(const Statement_inserter* inserter)
1401 { this->inserter_ = *inserter; }
1404 variable(Named_object*);
1407 constant(Named_object*, bool);
1410 function(Named_object*);
1413 statement(Block*, size_t* pindex, Statement*);
1416 expression(Expression**);
1421 // The function we are traversing.
1422 Named_object* function_;
1423 // Value to use for the predeclared constant iota.
1425 // Current statement inserter for use by expressions.
1426 Statement_inserter inserter_;
1432 Lower_parse_tree::variable(Named_object* no)
1434 if (!no->is_variable())
1435 return TRAVERSE_CONTINUE;
1437 if (no->is_variable() && no->var_value()->is_global())
1439 // Global variables can have loops in their initialization
1440 // expressions. This is handled in lower_init_expression.
1441 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1443 return TRAVERSE_CONTINUE;
1446 // This is a local variable. We are going to return
1447 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1448 // initialization expression when we reach the variable declaration
1449 // statement. However, that means that we need to traverse the type
1451 if (no->var_value()->has_type())
1453 Type* type = no->var_value()->type();
1456 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1457 return TRAVERSE_EXIT;
1460 go_assert(!no->var_value()->has_pre_init());
1462 return TRAVERSE_SKIP_COMPONENTS;
1465 // Lower constants. We handle constants specially so that we can set
1466 // the right value for the predeclared constant iota. This works in
1467 // conjunction with the way we lower Const_expression objects.
1470 Lower_parse_tree::constant(Named_object* no, bool)
1472 Named_constant* nc = no->const_value();
1474 // Don't get into trouble if the constant's initializer expression
1475 // refers to the constant itself.
1477 return TRAVERSE_CONTINUE;
1480 go_assert(this->iota_value_ == -1);
1481 this->iota_value_ = nc->iota_value();
1482 nc->traverse_expression(this);
1483 this->iota_value_ = -1;
1485 nc->clear_lowering();
1487 // We will traverse the expression a second time, but that will be
1490 return TRAVERSE_CONTINUE;
1493 // Lower function closure types. Record the function while lowering
1494 // it, so that we can pass it down when lowering an expression.
1497 Lower_parse_tree::function(Named_object* no)
1499 no->func_value()->set_closure_type();
1501 go_assert(this->function_ == NULL);
1502 this->function_ = no;
1503 int t = no->func_value()->traverse(this);
1504 this->function_ = NULL;
1506 if (t == TRAVERSE_EXIT)
1508 return TRAVERSE_SKIP_COMPONENTS;
1511 // Lower statement parse trees.
1514 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1516 // Because we explicitly traverse the statement's contents
1517 // ourselves, we want to skip block statements here. There is
1518 // nothing to lower in a block statement.
1519 if (sorig->is_block_statement())
1520 return TRAVERSE_CONTINUE;
1522 Statement_inserter hold_inserter(this->inserter_);
1523 this->inserter_ = Statement_inserter(block, pindex);
1525 // Lower the expressions first.
1526 int t = sorig->traverse_contents(this);
1527 if (t == TRAVERSE_EXIT)
1529 this->inserter_ = hold_inserter;
1533 // Keep lowering until nothing changes.
1534 Statement* s = sorig;
1537 Statement* snew = s->lower(this->gogo_, this->function_, block,
1542 t = s->traverse_contents(this);
1543 if (t == TRAVERSE_EXIT)
1545 this->inserter_ = hold_inserter;
1551 block->replace_statement(*pindex, s);
1553 this->inserter_ = hold_inserter;
1554 return TRAVERSE_SKIP_COMPONENTS;
1557 // Lower expression parse trees.
1560 Lower_parse_tree::expression(Expression** pexpr)
1562 // We have to lower all subexpressions first, so that we can get
1563 // their type if necessary. This is awkward, because we don't have
1564 // a postorder traversal pass.
1565 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1566 return TRAVERSE_EXIT;
1567 // Keep lowering until nothing changes.
1570 Expression* e = *pexpr;
1571 Expression* enew = e->lower(this->gogo_, this->function_,
1572 &this->inserter_, this->iota_value_);
1575 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
1576 return TRAVERSE_EXIT;
1579 return TRAVERSE_SKIP_COMPONENTS;
1582 // Lower the parse tree. This is called after the parse is complete,
1583 // when all names should be resolved.
1586 Gogo::lower_parse_tree()
1588 Lower_parse_tree lower_parse_tree(this, NULL);
1589 this->traverse(&lower_parse_tree);
1595 Gogo::lower_block(Named_object* function, Block* block)
1597 Lower_parse_tree lower_parse_tree(this, function);
1598 block->traverse(&lower_parse_tree);
1601 // Lower an expression. INSERTER may be NULL, in which case the
1602 // expression had better not need to create any temporaries.
1605 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1608 Lower_parse_tree lower_parse_tree(this, function);
1609 if (inserter != NULL)
1610 lower_parse_tree.set_inserter(inserter);
1611 lower_parse_tree.expression(pexpr);
1614 // Lower a constant. This is called when lowering a reference to a
1615 // constant. We have to make sure that the constant has already been
1619 Gogo::lower_constant(Named_object* no)
1621 go_assert(no->is_const());
1622 Lower_parse_tree lower(this, NULL);
1623 lower.constant(no, false);
1626 // Look for interface types to finalize methods of inherited
1629 class Finalize_methods : public Traverse
1632 Finalize_methods(Gogo* gogo)
1633 : Traverse(traverse_types),
1644 // Finalize the methods of an interface type.
1647 Finalize_methods::type(Type* t)
1649 // Check the classification so that we don't finalize the methods
1650 // twice for a named interface type.
1651 switch (t->classification())
1653 case Type::TYPE_INTERFACE:
1654 t->interface_type()->finalize_methods();
1657 case Type::TYPE_NAMED:
1659 // We have to finalize the methods of the real type first.
1660 // But if the real type is a struct type, then we only want to
1661 // finalize the methods of the field types, not of the struct
1662 // type itself. We don't want to add methods to the struct,
1663 // since it has a name.
1664 Named_type* nt = t->named_type();
1665 Type* rt = nt->real_type();
1666 if (rt->classification() != Type::TYPE_STRUCT)
1668 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1669 return TRAVERSE_EXIT;
1673 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1674 return TRAVERSE_EXIT;
1677 nt->finalize_methods(this->gogo_);
1679 // If this type is defined in a different package, then finalize the
1680 // types of all the methods, since we won't see them otherwise.
1681 if (nt->named_object()->package() != NULL && nt->has_any_methods())
1683 const Methods* methods = nt->methods();
1684 for (Methods::const_iterator p = methods->begin();
1685 p != methods->end();
1688 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1689 return TRAVERSE_EXIT;
1693 return TRAVERSE_SKIP_COMPONENTS;
1696 case Type::TYPE_STRUCT:
1697 // Traverse the field types first in case there is an embedded
1698 // field with methods that the struct should inherit.
1699 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1700 return TRAVERSE_EXIT;
1701 t->struct_type()->finalize_methods(this->gogo_);
1702 return TRAVERSE_SKIP_COMPONENTS;
1708 return TRAVERSE_CONTINUE;
1711 // Finalize method lists and build stub methods for types.
1714 Gogo::finalize_methods()
1716 Finalize_methods finalize(this);
1717 this->traverse(&finalize);
1720 // Set types for unspecified variables and constants.
1723 Gogo::determine_types()
1725 Bindings* bindings = this->current_bindings();
1726 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1727 p != bindings->end_definitions();
1730 if ((*p)->is_function())
1731 (*p)->func_value()->determine_types();
1732 else if ((*p)->is_variable())
1733 (*p)->var_value()->determine_type();
1734 else if ((*p)->is_const())
1735 (*p)->const_value()->determine_type();
1737 // See if a variable requires us to build an initialization
1738 // function. We know that we will see all global variables
1740 if (!this->need_init_fn_ && (*p)->is_variable())
1742 Variable* variable = (*p)->var_value();
1744 // If this is a global variable which requires runtime
1745 // initialization, we need an initialization function.
1746 if (!variable->is_global())
1748 else if (variable->init() == NULL)
1750 else if (variable->type()->interface_type() != NULL)
1751 this->need_init_fn_ = true;
1752 else if (variable->init()->is_constant())
1754 else if (!variable->init()->is_composite_literal())
1755 this->need_init_fn_ = true;
1756 else if (variable->init()->is_nonconstant_composite_literal())
1757 this->need_init_fn_ = true;
1759 // If this is a global variable which holds a pointer value,
1760 // then we need an initialization function to register it as a
1762 if (variable->is_global() && variable->type()->has_pointer())
1763 this->need_init_fn_ = true;
1767 // Determine the types of constants in packages.
1768 for (Packages::const_iterator p = this->packages_.begin();
1769 p != this->packages_.end();
1771 p->second->determine_types();
1774 // Traversal class used for type checking.
1776 class Check_types_traverse : public Traverse
1779 Check_types_traverse(Gogo* gogo)
1780 : Traverse(traverse_variables
1781 | traverse_constants
1782 | traverse_functions
1783 | traverse_statements
1784 | traverse_expressions),
1789 variable(Named_object*);
1792 constant(Named_object*, bool);
1795 function(Named_object*);
1798 statement(Block*, size_t* pindex, Statement*);
1801 expression(Expression**);
1808 // Check that a variable initializer has the right type.
1811 Check_types_traverse::variable(Named_object* named_object)
1813 if (named_object->is_variable())
1815 Variable* var = named_object->var_value();
1817 // Give error if variable type is not defined.
1818 var->type()->base();
1820 Expression* init = var->init();
1823 && !Type::are_assignable(var->type(), init->type(), &reason))
1826 error_at(var->location(), "incompatible type in initialization");
1828 error_at(var->location(),
1829 "incompatible type in initialization (%s)",
1833 else if (!var->is_used()
1834 && !var->is_global()
1835 && !var->is_parameter()
1836 && !var->is_receiver()
1837 && !var->type()->is_error()
1838 && (init == NULL || !init->is_error_expression())
1839 && !Lex::is_invalid_identifier(named_object->name()))
1840 error_at(var->location(), "%qs declared and not used",
1841 named_object->message_name().c_str());
1843 return TRAVERSE_CONTINUE;
1846 // Check that a constant initializer has the right type.
1849 Check_types_traverse::constant(Named_object* named_object, bool)
1851 Named_constant* constant = named_object->const_value();
1852 Type* ctype = constant->type();
1853 if (ctype->integer_type() == NULL
1854 && ctype->float_type() == NULL
1855 && ctype->complex_type() == NULL
1856 && !ctype->is_boolean_type()
1857 && !ctype->is_string_type())
1859 if (ctype->is_nil_type())
1860 error_at(constant->location(), "const initializer cannot be nil");
1861 else if (!ctype->is_error())
1862 error_at(constant->location(), "invalid constant type");
1863 constant->set_error();
1865 else if (!constant->expr()->is_constant())
1867 error_at(constant->expr()->location(), "expression is not constant");
1868 constant->set_error();
1870 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1873 error_at(constant->location(),
1874 "initialization expression has wrong type");
1875 constant->set_error();
1877 return TRAVERSE_CONTINUE;
1880 // There are no types to check in a function, but this is where we
1881 // issue warnings about labels which are defined but not referenced.
1884 Check_types_traverse::function(Named_object* no)
1886 no->func_value()->check_labels();
1887 return TRAVERSE_CONTINUE;
1890 // Check that types are valid in a statement.
1893 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1895 s->check_types(this->gogo_);
1896 return TRAVERSE_CONTINUE;
1899 // Check that types are valid in an expression.
1902 Check_types_traverse::expression(Expression** expr)
1904 (*expr)->check_types(this->gogo_);
1905 return TRAVERSE_CONTINUE;
1908 // Check that types are valid.
1913 Check_types_traverse traverse(this);
1914 this->traverse(&traverse);
1917 // Check the types in a single block.
1920 Gogo::check_types_in_block(Block* block)
1922 Check_types_traverse traverse(this);
1923 block->traverse(&traverse);
1926 // A traversal class used to find a single shortcut operator within an
1929 class Find_shortcut : public Traverse
1933 : Traverse(traverse_blocks
1934 | traverse_statements
1935 | traverse_expressions),
1939 // A pointer to the expression which was found, or NULL if none was
1943 { return this->found_; }
1948 { return TRAVERSE_SKIP_COMPONENTS; }
1951 statement(Block*, size_t*, Statement*)
1952 { return TRAVERSE_SKIP_COMPONENTS; }
1955 expression(Expression**);
1958 Expression** found_;
1961 // Find a shortcut expression.
1964 Find_shortcut::expression(Expression** pexpr)
1966 Expression* expr = *pexpr;
1967 Binary_expression* be = expr->binary_expression();
1969 return TRAVERSE_CONTINUE;
1970 Operator op = be->op();
1971 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1972 return TRAVERSE_CONTINUE;
1973 go_assert(this->found_ == NULL);
1974 this->found_ = pexpr;
1975 return TRAVERSE_EXIT;
1978 // A traversal class used to turn shortcut operators into explicit if
1981 class Shortcuts : public Traverse
1984 Shortcuts(Gogo* gogo)
1985 : Traverse(traverse_variables
1986 | traverse_statements),
1992 variable(Named_object*);
1995 statement(Block*, size_t*, Statement*);
1998 // Convert a shortcut operator.
2000 convert_shortcut(Block* enclosing, Expression** pshortcut);
2006 // Remove shortcut operators in a single statement.
2009 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
2011 // FIXME: This approach doesn't work for switch statements, because
2012 // we add the new statements before the whole switch when we need to
2013 // instead add them just before the switch expression. The right
2014 // fix is probably to lower switch statements with nonconstant cases
2015 // to a series of conditionals.
2016 if (s->switch_statement() != NULL)
2017 return TRAVERSE_CONTINUE;
2021 Find_shortcut find_shortcut;
2023 // If S is a variable declaration, then ordinary traversal won't
2024 // do anything. We want to explicitly traverse the
2025 // initialization expression if there is one.
2026 Variable_declaration_statement* vds = s->variable_declaration_statement();
2027 Expression* init = NULL;
2029 s->traverse_contents(&find_shortcut);
2032 init = vds->var()->var_value()->init();
2034 return TRAVERSE_CONTINUE;
2035 init->traverse(&init, &find_shortcut);
2037 Expression** pshortcut = find_shortcut.found();
2038 if (pshortcut == NULL)
2039 return TRAVERSE_CONTINUE;
2041 Statement* snew = this->convert_shortcut(block, pshortcut);
2042 block->insert_statement_before(*pindex, snew);
2045 if (pshortcut == &init)
2046 vds->var()->var_value()->set_init(init);
2050 // Remove shortcut operators in the initializer of a global variable.
2053 Shortcuts::variable(Named_object* no)
2055 if (no->is_result_variable())
2056 return TRAVERSE_CONTINUE;
2057 Variable* var = no->var_value();
2058 Expression* init = var->init();
2059 if (!var->is_global() || init == NULL)
2060 return TRAVERSE_CONTINUE;
2064 Find_shortcut find_shortcut;
2065 init->traverse(&init, &find_shortcut);
2066 Expression** pshortcut = find_shortcut.found();
2067 if (pshortcut == NULL)
2068 return TRAVERSE_CONTINUE;
2070 Statement* snew = this->convert_shortcut(NULL, pshortcut);
2071 var->add_preinit_statement(this->gogo_, snew);
2072 if (pshortcut == &init)
2073 var->set_init(init);
2077 // Given an expression which uses a shortcut operator, return a
2078 // statement which implements it, and update *PSHORTCUT accordingly.
2081 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
2083 Binary_expression* shortcut = (*pshortcut)->binary_expression();
2084 Expression* left = shortcut->left();
2085 Expression* right = shortcut->right();
2086 Location loc = shortcut->location();
2088 Block* retblock = new Block(enclosing, loc);
2089 retblock->set_end_location(loc);
2091 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
2093 retblock->add_statement(ts);
2095 Block* block = new Block(retblock, loc);
2096 block->set_end_location(loc);
2097 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
2098 Statement* assign = Statement::make_assignment(tmpref, right, loc);
2099 block->add_statement(assign);
2101 Expression* cond = Expression::make_temporary_reference(ts, loc);
2102 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
2103 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
2105 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
2107 retblock->add_statement(if_statement);
2109 *pshortcut = Expression::make_temporary_reference(ts, loc);
2113 // Now convert any shortcut operators in LEFT and RIGHT.
2114 Shortcuts shortcuts(this->gogo_);
2115 retblock->traverse(&shortcuts);
2117 return Statement::make_block_statement(retblock, loc);
2120 // Turn shortcut operators into explicit if statements. Doing this
2121 // considerably simplifies the order of evaluation rules.
2124 Gogo::remove_shortcuts()
2126 Shortcuts shortcuts(this);
2127 this->traverse(&shortcuts);
2130 // A traversal class which finds all the expressions which must be
2131 // evaluated in order within a statement or larger expression. This
2132 // is used to implement the rules about order of evaluation.
2134 class Find_eval_ordering : public Traverse
2137 typedef std::vector<Expression**> Expression_pointers;
2140 Find_eval_ordering()
2141 : Traverse(traverse_blocks
2142 | traverse_statements
2143 | traverse_expressions),
2149 { return this->exprs_.size(); }
2151 typedef Expression_pointers::const_iterator const_iterator;
2155 { return this->exprs_.begin(); }
2159 { return this->exprs_.end(); }
2164 { return TRAVERSE_SKIP_COMPONENTS; }
2167 statement(Block*, size_t*, Statement*)
2168 { return TRAVERSE_SKIP_COMPONENTS; }
2171 expression(Expression**);
2174 // A list of pointers to expressions with side-effects.
2175 Expression_pointers exprs_;
2178 // If an expression must be evaluated in order, put it on the list.
2181 Find_eval_ordering::expression(Expression** expression_pointer)
2183 // We have to look at subexpressions before this one.
2184 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2185 return TRAVERSE_EXIT;
2186 if ((*expression_pointer)->must_eval_in_order())
2187 this->exprs_.push_back(expression_pointer);
2188 return TRAVERSE_SKIP_COMPONENTS;
2191 // A traversal class for ordering evaluations.
2193 class Order_eval : public Traverse
2196 Order_eval(Gogo* gogo)
2197 : Traverse(traverse_variables
2198 | traverse_statements),
2203 variable(Named_object*);
2206 statement(Block*, size_t*, Statement*);
2213 // Implement the order of evaluation rules for a statement.
2216 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2218 // FIXME: This approach doesn't work for switch statements, because
2219 // we add the new statements before the whole switch when we need to
2220 // instead add them just before the switch expression. The right
2221 // fix is probably to lower switch statements with nonconstant cases
2222 // to a series of conditionals.
2223 if (s->switch_statement() != NULL)
2224 return TRAVERSE_CONTINUE;
2226 Find_eval_ordering find_eval_ordering;
2228 // If S is a variable declaration, then ordinary traversal won't do
2229 // anything. We want to explicitly traverse the initialization
2230 // expression if there is one.
2231 Variable_declaration_statement* vds = s->variable_declaration_statement();
2232 Expression* init = NULL;
2233 Expression* orig_init = NULL;
2235 s->traverse_contents(&find_eval_ordering);
2238 init = vds->var()->var_value()->init();
2240 return TRAVERSE_CONTINUE;
2243 // It might seem that this could be
2244 // init->traverse_subexpressions. Unfortunately that can fail
2247 // newvar, err := call(arg())
2248 // Here newvar will have an init of call result 0 of
2249 // call(arg()). If we only traverse subexpressions, we will
2250 // only find arg(), and we won't bother to move anything out.
2251 // Then we get to the assignment to err, we will traverse the
2252 // whole statement, and this time we will find both call() and
2253 // arg(), and so we will move them out. This will cause them to
2254 // be put into temporary variables before the assignment to err
2255 // but after the declaration of newvar. To avoid that problem,
2256 // we traverse the entire expression here.
2257 Expression::traverse(&init, &find_eval_ordering);
2260 size_t c = find_eval_ordering.size();
2262 return TRAVERSE_CONTINUE;
2264 // If there is only one expression with a side-effect, we can
2265 // usually leave it in place. However, for an assignment statement,
2266 // we need to evaluate an expression on the right hand side before
2267 // we evaluate any index expression on the left hand side, so for
2268 // that case we always move the expression. Otherwise we mishandle
2269 // m[0] = len(m) where m is a map.
2270 if (c == 1 && s->classification() != Statement::STATEMENT_ASSIGNMENT)
2271 return TRAVERSE_CONTINUE;
2273 bool is_thunk = s->thunk_statement() != NULL;
2274 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2275 p != find_eval_ordering.end();
2278 Expression** pexpr = *p;
2280 // The last expression in a thunk will be the call passed to go
2281 // or defer, which we must not evaluate early.
2282 if (is_thunk && p + 1 == find_eval_ordering.end())
2285 Location loc = (*pexpr)->location();
2287 if ((*pexpr)->call_expression() == NULL
2288 || (*pexpr)->call_expression()->result_count() < 2)
2290 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2293 *pexpr = Expression::make_temporary_reference(ts, loc);
2297 // A call expression which returns multiple results needs to
2298 // be handled specially. We can't create a temporary
2299 // because there is no type to give it. Any actual uses of
2300 // the values will be done via Call_result_expressions.
2301 s = Statement::make_statement(*pexpr, true);
2304 block->insert_statement_before(*pindex, s);
2308 if (init != orig_init)
2309 vds->var()->var_value()->set_init(init);
2311 return TRAVERSE_CONTINUE;
2314 // Implement the order of evaluation rules for the initializer of a
2318 Order_eval::variable(Named_object* no)
2320 if (no->is_result_variable())
2321 return TRAVERSE_CONTINUE;
2322 Variable* var = no->var_value();
2323 Expression* init = var->init();
2324 if (!var->is_global() || init == NULL)
2325 return TRAVERSE_CONTINUE;
2327 Find_eval_ordering find_eval_ordering;
2328 Expression::traverse(&init, &find_eval_ordering);
2330 if (find_eval_ordering.size() <= 1)
2332 // If there is only one expression with a side-effect, we can
2333 // leave it in place.
2334 return TRAVERSE_SKIP_COMPONENTS;
2337 Expression* orig_init = init;
2339 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2340 p != find_eval_ordering.end();
2343 Expression** pexpr = *p;
2344 Location loc = (*pexpr)->location();
2346 if ((*pexpr)->call_expression() == NULL
2347 || (*pexpr)->call_expression()->result_count() < 2)
2349 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2352 *pexpr = Expression::make_temporary_reference(ts, loc);
2356 // A call expression which returns multiple results needs to
2357 // be handled specially.
2358 s = Statement::make_statement(*pexpr, true);
2360 var->add_preinit_statement(this->gogo_, s);
2363 if (init != orig_init)
2364 var->set_init(init);
2366 return TRAVERSE_SKIP_COMPONENTS;
2369 // Use temporary variables to implement the order of evaluation rules.
2372 Gogo::order_evaluations()
2374 Order_eval order_eval(this);
2375 this->traverse(&order_eval);
2378 // Traversal to convert calls to the predeclared recover function to
2379 // pass in an argument indicating whether it can recover from a panic
2382 class Convert_recover : public Traverse
2385 Convert_recover(Named_object* arg)
2386 : Traverse(traverse_expressions),
2392 expression(Expression**);
2395 // The argument to pass to the function.
2399 // Convert calls to recover.
2402 Convert_recover::expression(Expression** pp)
2404 Call_expression* ce = (*pp)->call_expression();
2405 if (ce != NULL && ce->is_recover_call())
2406 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2408 return TRAVERSE_CONTINUE;
2411 // Traversal for build_recover_thunks.
2413 class Build_recover_thunks : public Traverse
2416 Build_recover_thunks(Gogo* gogo)
2417 : Traverse(traverse_functions),
2422 function(Named_object*);
2426 can_recover_arg(Location);
2432 // If this function calls recover, turn it into a thunk.
2435 Build_recover_thunks::function(Named_object* orig_no)
2437 Function* orig_func = orig_no->func_value();
2438 if (!orig_func->calls_recover()
2439 || orig_func->is_recover_thunk()
2440 || orig_func->has_recover_thunk())
2441 return TRAVERSE_CONTINUE;
2443 Gogo* gogo = this->gogo_;
2444 Location location = orig_func->location();
2449 Function_type* orig_fntype = orig_func->type();
2450 Typed_identifier_list* new_params = new Typed_identifier_list();
2451 std::string receiver_name;
2452 if (orig_fntype->is_method())
2454 const Typed_identifier* receiver = orig_fntype->receiver();
2455 snprintf(buf, sizeof buf, "rt.%u", count);
2457 receiver_name = buf;
2458 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2459 receiver->location()));
2461 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2462 if (orig_params != NULL && !orig_params->empty())
2464 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2465 p != orig_params->end();
2468 snprintf(buf, sizeof buf, "pt.%u", count);
2470 new_params->push_back(Typed_identifier(buf, p->type(),
2474 snprintf(buf, sizeof buf, "pr.%u", count);
2476 std::string can_recover_name = buf;
2477 new_params->push_back(Typed_identifier(can_recover_name,
2478 Type::lookup_bool_type(),
2479 orig_fntype->location()));
2481 const Typed_identifier_list* orig_results = orig_fntype->results();
2482 Typed_identifier_list* new_results;
2483 if (orig_results == NULL || orig_results->empty())
2487 new_results = new Typed_identifier_list();
2488 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2489 p != orig_results->end();
2491 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2494 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2496 orig_fntype->location());
2497 if (orig_fntype->is_varargs())
2498 new_fntype->set_is_varargs();
2500 std::string name = orig_no->name() + "$recover";
2501 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2503 Function *new_func = new_no->func_value();
2504 if (orig_func->enclosing() != NULL)
2505 new_func->set_enclosing(orig_func->enclosing());
2507 // We build the code for the original function attached to the new
2508 // function, and then swap the original and new function bodies.
2509 // This means that existing references to the original function will
2510 // then refer to the new function. That makes this code a little
2511 // confusing, in that the reference to NEW_NO really refers to the
2512 // other function, not the one we are building.
2514 Expression* closure = NULL;
2515 if (orig_func->needs_closure())
2517 Named_object* orig_closure_no = orig_func->closure_var();
2518 Variable* orig_closure_var = orig_closure_no->var_value();
2519 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2520 true, false, location);
2521 snprintf(buf, sizeof buf, "closure.%u", count);
2523 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2525 new_func->set_closure_var(new_closure_no);
2526 closure = Expression::make_var_reference(new_closure_no, location);
2529 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2531 Expression_list* args = new Expression_list();
2532 if (new_params != NULL)
2534 // Note that we skip the last parameter, which is the boolean
2535 // indicating whether recover can succed.
2536 for (Typed_identifier_list::const_iterator p = new_params->begin();
2537 p + 1 != new_params->end();
2540 Named_object* p_no = gogo->lookup(p->name(), NULL);
2541 go_assert(p_no != NULL
2542 && p_no->is_variable()
2543 && p_no->var_value()->is_parameter());
2544 args->push_back(Expression::make_var_reference(p_no, location));
2547 args->push_back(this->can_recover_arg(location));
2549 gogo->start_block(location);
2551 Call_expression* call = Expression::make_call(fn, args, false, location);
2553 // Any varargs call has already been lowered.
2554 call->set_varargs_are_lowered();
2557 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2558 s = Statement::make_statement(call, true);
2561 Expression_list* vals = new Expression_list();
2562 size_t rc = orig_fntype->results()->size();
2564 vals->push_back(call);
2567 for (size_t i = 0; i < rc; ++i)
2568 vals->push_back(Expression::make_call_result(call, i));
2570 s = Statement::make_return_statement(vals, location);
2572 s->determine_types();
2573 gogo->add_statement(s);
2575 Block* b = gogo->finish_block(location);
2577 gogo->add_block(b, location);
2579 // Lower the call in case it returns multiple results.
2580 gogo->lower_block(new_no, b);
2582 gogo->finish_function(location);
2584 // Swap the function bodies and types.
2585 new_func->swap_for_recover(orig_func);
2586 orig_func->set_is_recover_thunk();
2587 new_func->set_calls_recover();
2588 new_func->set_has_recover_thunk();
2590 Bindings* orig_bindings = orig_func->block()->bindings();
2591 Bindings* new_bindings = new_func->block()->bindings();
2592 if (orig_fntype->is_method())
2594 // We changed the receiver to be a regular parameter. We have
2595 // to update the binding accordingly in both functions.
2596 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2597 go_assert(orig_rec_no != NULL
2598 && orig_rec_no->is_variable()
2599 && !orig_rec_no->var_value()->is_receiver());
2600 orig_rec_no->var_value()->set_is_receiver();
2602 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2603 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2604 if (new_rec_no == NULL)
2605 go_assert(saw_errors());
2608 go_assert(new_rec_no->is_variable()
2609 && new_rec_no->var_value()->is_receiver());
2610 new_rec_no->var_value()->set_is_not_receiver();
2614 // Because we flipped blocks but not types, the can_recover
2615 // parameter appears in the (now) old bindings as a parameter.
2616 // Change it to a local variable, whereupon it will be discarded.
2617 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2618 go_assert(can_recover_no != NULL
2619 && can_recover_no->is_variable()
2620 && can_recover_no->var_value()->is_parameter());
2621 orig_bindings->remove_binding(can_recover_no);
2623 // Add the can_recover argument to the (now) new bindings, and
2624 // attach it to any recover statements.
2625 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2626 false, true, false, location);
2627 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2629 Convert_recover convert_recover(can_recover_no);
2630 new_func->traverse(&convert_recover);
2632 // Update the function pointers in any named results.
2633 new_func->update_result_variables();
2634 orig_func->update_result_variables();
2636 return TRAVERSE_CONTINUE;
2639 // Return the expression to pass for the .can_recover parameter to the
2640 // new function. This indicates whether a call to recover may return
2641 // non-nil. The expression is
2642 // __go_can_recover(__builtin_return_address()).
2645 Build_recover_thunks::can_recover_arg(Location location)
2647 static Named_object* builtin_return_address;
2648 if (builtin_return_address == NULL)
2650 const Location bloc = Linemap::predeclared_location();
2652 Typed_identifier_list* param_types = new Typed_identifier_list();
2653 Type* uint_type = Type::lookup_integer_type("uint");
2654 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2656 Typed_identifier_list* return_types = new Typed_identifier_list();
2657 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2658 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2660 Function_type* fntype = Type::make_function_type(NULL, param_types,
2661 return_types, bloc);
2662 builtin_return_address =
2663 Named_object::make_function_declaration("__builtin_return_address",
2664 NULL, fntype, bloc);
2665 const char* n = "__builtin_return_address";
2666 builtin_return_address->func_declaration_value()->set_asm_name(n);
2669 static Named_object* can_recover;
2670 if (can_recover == NULL)
2672 const Location bloc = Linemap::predeclared_location();
2673 Typed_identifier_list* param_types = new Typed_identifier_list();
2674 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2675 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2676 Type* boolean_type = Type::lookup_bool_type();
2677 Typed_identifier_list* results = new Typed_identifier_list();
2678 results->push_back(Typed_identifier("", boolean_type, bloc));
2679 Function_type* fntype = Type::make_function_type(NULL, param_types,
2681 can_recover = Named_object::make_function_declaration("__go_can_recover",
2684 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2687 Expression* fn = Expression::make_func_reference(builtin_return_address,
2691 mpz_init_set_ui(zval, 0UL);
2692 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2694 Expression_list *args = new Expression_list();
2695 args->push_back(zexpr);
2697 Expression* call = Expression::make_call(fn, args, false, location);
2699 args = new Expression_list();
2700 args->push_back(call);
2702 fn = Expression::make_func_reference(can_recover, NULL, location);
2703 return Expression::make_call(fn, args, false, location);
2706 // Build thunks for functions which call recover. We build a new
2707 // function with an extra parameter, which is whether a call to
2708 // recover can succeed. We then move the body of this function to
2709 // that one. We then turn this function into a thunk which calls the
2710 // new one, passing the value of
2711 // __go_can_recover(__builtin_return_address()). The function will be
2712 // marked as not splitting the stack. This will cooperate with the
2713 // implementation of defer to make recover do the right thing.
2716 Gogo::build_recover_thunks()
2718 Build_recover_thunks build_recover_thunks(this);
2719 this->traverse(&build_recover_thunks);
2722 // Look for named types to see whether we need to create an interface
2725 class Build_method_tables : public Traverse
2728 Build_method_tables(Gogo* gogo,
2729 const std::vector<Interface_type*>& interfaces)
2730 : Traverse(traverse_types),
2731 gogo_(gogo), interfaces_(interfaces)
2740 // A list of locally defined interfaces which have hidden methods.
2741 const std::vector<Interface_type*>& interfaces_;
2744 // Build all required interface method tables for types. We need to
2745 // ensure that we have an interface method table for every interface
2746 // which has a hidden method, for every named type which implements
2747 // that interface. Normally we can just build interface method tables
2748 // as we need them. However, in some cases we can require an
2749 // interface method table for an interface defined in a different
2750 // package for a type defined in that package. If that interface and
2751 // type both use a hidden method, that is OK. However, we will not be
2752 // able to build that interface method table when we need it, because
2753 // the type's hidden method will be static. So we have to build it
2754 // here, and just refer it from other packages as needed.
2757 Gogo::build_interface_method_tables()
2762 std::vector<Interface_type*> hidden_interfaces;
2763 hidden_interfaces.reserve(this->interface_types_.size());
2764 for (std::vector<Interface_type*>::const_iterator pi =
2765 this->interface_types_.begin();
2766 pi != this->interface_types_.end();
2769 const Typed_identifier_list* methods = (*pi)->methods();
2770 if (methods == NULL)
2772 for (Typed_identifier_list::const_iterator pm = methods->begin();
2773 pm != methods->end();
2776 if (Gogo::is_hidden_name(pm->name()))
2778 hidden_interfaces.push_back(*pi);
2784 if (!hidden_interfaces.empty())
2786 // Now traverse the tree looking for all named types.
2787 Build_method_tables bmt(this, hidden_interfaces);
2788 this->traverse(&bmt);
2791 // We no longer need the list of interfaces.
2793 this->interface_types_.clear();
2796 // This is called for each type. For a named type, for each of the
2797 // interfaces with hidden methods that it implements, create the
2801 Build_method_tables::type(Type* type)
2803 Named_type* nt = type->named_type();
2806 for (std::vector<Interface_type*>::const_iterator p =
2807 this->interfaces_.begin();
2808 p != this->interfaces_.end();
2811 // We ask whether a pointer to the named type implements the
2812 // interface, because a pointer can implement more methods
2814 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2816 nt->interface_method_table(this->gogo_, *p, false);
2817 nt->interface_method_table(this->gogo_, *p, true);
2821 return TRAVERSE_CONTINUE;
2824 // Traversal class used to check for return statements.
2826 class Check_return_statements_traverse : public Traverse
2829 Check_return_statements_traverse()
2830 : Traverse(traverse_functions)
2834 function(Named_object*);
2837 // Check that a function has a return statement if it needs one.
2840 Check_return_statements_traverse::function(Named_object* no)
2842 Function* func = no->func_value();
2843 const Function_type* fntype = func->type();
2844 const Typed_identifier_list* results = fntype->results();
2846 // We only need a return statement if there is a return value.
2847 if (results == NULL || results->empty())
2848 return TRAVERSE_CONTINUE;
2850 if (func->block()->may_fall_through())
2851 error_at(func->location(), "control reaches end of non-void function");
2853 return TRAVERSE_CONTINUE;
2856 // Check return statements.
2859 Gogo::check_return_statements()
2861 Check_return_statements_traverse traverse;
2862 this->traverse(&traverse);
2865 // Work out the package priority. It is one more than the maximum
2866 // priority of an imported package.
2869 Gogo::package_priority() const
2872 for (Packages::const_iterator p = this->packages_.begin();
2873 p != this->packages_.end();
2875 if (p->second->priority() > priority)
2876 priority = p->second->priority();
2877 return priority + 1;
2880 // Export identifiers as requested.
2885 // For now we always stream to a section. Later we may want to
2886 // support streaming to a separate file.
2887 Stream_to_section stream;
2889 Export exp(&stream);
2890 exp.register_builtin_types(this);
2891 exp.export_globals(this->package_name(),
2893 this->package_priority(),
2895 (this->need_init_fn_ && !this->is_main_package()
2896 ? this->get_init_fn_name()
2898 this->imported_init_fns_,
2899 this->package_->bindings());
2902 // Find the blocks in order to convert named types defined in blocks.
2904 class Convert_named_types : public Traverse
2907 Convert_named_types(Gogo* gogo)
2908 : Traverse(traverse_blocks),
2914 block(Block* block);
2921 Convert_named_types::block(Block* block)
2923 this->gogo_->convert_named_types_in_bindings(block->bindings());
2924 return TRAVERSE_CONTINUE;
2927 // Convert all named types to the backend representation. Since named
2928 // types can refer to other types, this needs to be done in the right
2929 // sequence, which is handled by Named_type::convert. Here we arrange
2930 // to call that for each named type.
2933 Gogo::convert_named_types()
2935 this->convert_named_types_in_bindings(this->globals_);
2936 for (Packages::iterator p = this->packages_.begin();
2937 p != this->packages_.end();
2940 Package* package = p->second;
2941 this->convert_named_types_in_bindings(package->bindings());
2944 Convert_named_types cnt(this);
2945 this->traverse(&cnt);
2947 // Make all the builtin named types used for type descriptors, and
2948 // then convert them. They will only be written out if they are
2950 Type::make_type_descriptor_type();
2951 Type::make_type_descriptor_ptr_type();
2952 Function_type::make_function_type_descriptor_type();
2953 Pointer_type::make_pointer_type_descriptor_type();
2954 Struct_type::make_struct_type_descriptor_type();
2955 Array_type::make_array_type_descriptor_type();
2956 Array_type::make_slice_type_descriptor_type();
2957 Map_type::make_map_type_descriptor_type();
2958 Map_type::make_map_descriptor_type();
2959 Channel_type::make_chan_type_descriptor_type();
2960 Interface_type::make_interface_type_descriptor_type();
2961 Type::convert_builtin_named_types(this);
2963 Runtime::convert_types(this);
2965 this->named_types_are_converted_ = true;
2968 // Convert all names types in a set of bindings.
2971 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2973 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2974 p != bindings->end_definitions();
2977 if ((*p)->is_type())
2978 (*p)->type_value()->convert(this);
2984 Function::Function(Function_type* type, Function* enclosing, Block* block,
2986 : type_(type), enclosing_(enclosing), results_(NULL),
2987 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2988 defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2989 is_recover_thunk_(false), has_recover_thunk_(false)
2993 // Create the named result variables.
2996 Function::create_result_variables(Gogo* gogo)
2998 const Typed_identifier_list* results = this->type_->results();
2999 if (results == NULL || results->empty())
3002 if (!results->front().name().empty())
3003 this->results_are_named_ = true;
3005 this->results_ = new Results();
3006 this->results_->reserve(results->size());
3008 Block* block = this->block_;
3010 for (Typed_identifier_list::const_iterator p = results->begin();
3011 p != results->end();
3014 std::string name = p->name();
3015 if (name.empty() || Gogo::is_sink_name(name))
3017 static int result_counter;
3019 snprintf(buf, sizeof buf, "$ret%d", result_counter);
3021 name = gogo->pack_hidden_name(buf, false);
3023 Result_variable* result = new Result_variable(p->type(), this, index,
3025 Named_object* no = block->bindings()->add_result_variable(name, result);
3026 if (no->is_result_variable())
3027 this->results_->push_back(no);
3030 static int dummy_result_count;
3032 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
3033 ++dummy_result_count;
3034 name = gogo->pack_hidden_name(buf, false);
3035 no = block->bindings()->add_result_variable(name, result);
3036 go_assert(no->is_result_variable());
3037 this->results_->push_back(no);
3042 // Update the named result variables when cloning a function which
3046 Function::update_result_variables()
3048 if (this->results_ == NULL)
3051 for (Results::iterator p = this->results_->begin();
3052 p != this->results_->end();
3054 (*p)->result_var_value()->set_function(this);
3057 // Return the closure variable, creating it if necessary.
3060 Function::closure_var()
3062 if (this->closure_var_ == NULL)
3064 // We don't know the type of the variable yet. We add fields as
3066 Location loc = this->type_->location();
3067 Struct_field_list* sfl = new Struct_field_list;
3068 Type* struct_type = Type::make_struct_type(sfl, loc);
3069 Variable* var = new Variable(Type::make_pointer_type(struct_type),
3070 NULL, false, true, false, loc);
3072 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
3073 // Note that the new variable is not in any binding contour.
3075 return this->closure_var_;
3078 // Set the type of the closure variable.
3081 Function::set_closure_type()
3083 if (this->closure_var_ == NULL)
3085 Named_object* closure = this->closure_var_;
3086 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3087 unsigned int index = 0;
3088 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3089 p != this->closure_fields_.end();
3092 Named_object* no = p->first;
3094 snprintf(buf, sizeof buf, "%u", index);
3095 std::string n = no->name() + buf;
3097 if (no->is_variable())
3098 var_type = no->var_value()->type();
3100 var_type = no->result_var_value()->type();
3101 Type* field_type = Type::make_pointer_type(var_type);
3102 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3106 // Return whether this function is a method.
3109 Function::is_method() const
3111 return this->type_->is_method();
3114 // Add a label definition.
3117 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3120 Label* lnull = NULL;
3121 std::pair<Labels::iterator, bool> ins =
3122 this->labels_.insert(std::make_pair(label_name, lnull));
3126 // This is a new label.
3127 label = new Label(label_name);
3128 ins.first->second = label;
3132 // The label was already in the hash table.
3133 label = ins.first->second;
3134 if (label->is_defined())
3136 error_at(location, "label %qs already defined",
3137 Gogo::message_name(label_name).c_str());
3138 inform(label->location(), "previous definition of %qs was here",
3139 Gogo::message_name(label_name).c_str());
3140 return new Label(label_name);
3144 label->define(location, gogo->bindings_snapshot(location));
3146 // Issue any errors appropriate for any previous goto's to this
3148 const std::vector<Bindings_snapshot*>& refs(label->refs());
3149 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3152 (*p)->check_goto_to(gogo->current_block());
3153 label->clear_refs();
3158 // Add a reference to a label.
3161 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3162 Location location, bool issue_goto_errors)
3164 Label* lnull = NULL;
3165 std::pair<Labels::iterator, bool> ins =
3166 this->labels_.insert(std::make_pair(label_name, lnull));
3170 // The label was already in the hash table.
3171 label = ins.first->second;
3175 go_assert(ins.first->second == NULL);
3176 label = new Label(label_name);
3177 ins.first->second = label;
3180 label->set_is_used();
3182 if (issue_goto_errors)
3184 Bindings_snapshot* snapshot = label->snapshot();
3185 if (snapshot != NULL)
3186 snapshot->check_goto_from(gogo->current_block(), location);
3188 label->add_snapshot_ref(gogo->bindings_snapshot(location));
3194 // Warn about labels that are defined but not used.
3197 Function::check_labels() const
3199 for (Labels::const_iterator p = this->labels_.begin();
3200 p != this->labels_.end();
3203 Label* label = p->second;
3204 if (!label->is_used())
3205 error_at(label->location(), "label %qs defined and not used",
3206 Gogo::message_name(label->name()).c_str());
3210 // Swap one function with another. This is used when building the
3211 // thunk we use to call a function which calls recover. It may not
3212 // work for any other case.
3215 Function::swap_for_recover(Function *x)
3217 go_assert(this->enclosing_ == x->enclosing_);
3218 std::swap(this->results_, x->results_);
3219 std::swap(this->closure_var_, x->closure_var_);
3220 std::swap(this->block_, x->block_);
3221 go_assert(this->location_ == x->location_);
3222 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3223 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3226 // Traverse the tree.
3229 Function::traverse(Traverse* traverse)
3231 unsigned int traverse_mask = traverse->traverse_mask();
3234 & (Traverse::traverse_types | Traverse::traverse_expressions))
3237 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3238 return TRAVERSE_EXIT;
3241 // FIXME: We should check traverse_functions here if nested
3242 // functions are stored in block bindings.
3243 if (this->block_ != NULL
3245 & (Traverse::traverse_variables
3246 | Traverse::traverse_constants
3247 | Traverse::traverse_blocks
3248 | Traverse::traverse_statements
3249 | Traverse::traverse_expressions
3250 | Traverse::traverse_types)) != 0)
3252 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3253 return TRAVERSE_EXIT;
3256 return TRAVERSE_CONTINUE;
3259 // Work out types for unspecified variables and constants.
3262 Function::determine_types()
3264 if (this->block_ != NULL)
3265 this->block_->determine_types();
3268 // Get a pointer to the variable representing the defer stack for this
3269 // function, making it if necessary. The value of the variable is set
3270 // by the runtime routines to true if the function is returning,
3271 // rather than panicing through. A pointer to this variable is used
3272 // as a marker for the functions on the defer stack associated with
3273 // this function. A function-specific variable permits inlining a
3274 // function which uses defer.
3277 Function::defer_stack(Location location)
3279 if (this->defer_stack_ == NULL)
3281 Type* t = Type::lookup_bool_type();
3282 Expression* n = Expression::make_boolean(false, location);
3283 this->defer_stack_ = Statement::make_temporary(t, n, location);
3284 this->defer_stack_->set_is_address_taken();
3286 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3288 return Expression::make_unary(OPERATOR_AND, ref, location);
3291 // Export the function.
3294 Function::export_func(Export* exp, const std::string& name) const
3296 Function::export_func_with_type(exp, name, this->type_);
3299 // Export a function with a type.
3302 Function::export_func_with_type(Export* exp, const std::string& name,
3303 const Function_type* fntype)
3305 exp->write_c_string("func ");
3307 if (fntype->is_method())
3309 exp->write_c_string("(");
3310 const Typed_identifier* receiver = fntype->receiver();
3311 exp->write_name(receiver->name());
3312 exp->write_c_string(" ");
3313 exp->write_type(receiver->type());
3314 exp->write_c_string(") ");
3317 exp->write_string(name);
3319 exp->write_c_string(" (");
3320 const Typed_identifier_list* parameters = fntype->parameters();
3321 if (parameters != NULL)
3323 bool is_varargs = fntype->is_varargs();
3325 for (Typed_identifier_list::const_iterator p = parameters->begin();
3326 p != parameters->end();
3332 exp->write_c_string(", ");
3333 exp->write_name(p->name());
3334 exp->write_c_string(" ");
3335 if (!is_varargs || p + 1 != parameters->end())
3336 exp->write_type(p->type());
3339 exp->write_c_string("...");
3340 exp->write_type(p->type()->array_type()->element_type());
3344 exp->write_c_string(")");
3346 const Typed_identifier_list* results = fntype->results();
3347 if (results != NULL)
3349 if (results->size() == 1 && results->begin()->name().empty())
3351 exp->write_c_string(" ");
3352 exp->write_type(results->begin()->type());
3356 exp->write_c_string(" (");
3358 for (Typed_identifier_list::const_iterator p = results->begin();
3359 p != results->end();
3365 exp->write_c_string(", ");
3366 exp->write_name(p->name());
3367 exp->write_c_string(" ");
3368 exp->write_type(p->type());
3370 exp->write_c_string(")");
3373 exp->write_c_string(";\n");
3376 // Import a function.
3379 Function::import_func(Import* imp, std::string* pname,
3380 Typed_identifier** preceiver,
3381 Typed_identifier_list** pparameters,
3382 Typed_identifier_list** presults,
3385 imp->require_c_string("func ");
3388 if (imp->peek_char() == '(')
3390 imp->require_c_string("(");
3391 std::string name = imp->read_name();
3392 imp->require_c_string(" ");
3393 Type* rtype = imp->read_type();
3394 *preceiver = new Typed_identifier(name, rtype, imp->location());
3395 imp->require_c_string(") ");
3398 *pname = imp->read_identifier();
3400 Typed_identifier_list* parameters;
3401 *is_varargs = false;
3402 imp->require_c_string(" (");
3403 if (imp->peek_char() == ')')
3407 parameters = new Typed_identifier_list();
3410 std::string name = imp->read_name();
3411 imp->require_c_string(" ");
3413 if (imp->match_c_string("..."))
3419 Type* ptype = imp->read_type();
3421 ptype = Type::make_array_type(ptype, NULL);
3422 parameters->push_back(Typed_identifier(name, ptype,
3424 if (imp->peek_char() != ',')
3426 go_assert(!*is_varargs);
3427 imp->require_c_string(", ");
3430 imp->require_c_string(")");
3431 *pparameters = parameters;
3433 Typed_identifier_list* results;
3434 if (imp->peek_char() != ' ')
3438 results = new Typed_identifier_list();
3439 imp->require_c_string(" ");
3440 if (imp->peek_char() != '(')
3442 Type* rtype = imp->read_type();
3443 results->push_back(Typed_identifier("", rtype, imp->location()));
3447 imp->require_c_string("(");
3450 std::string name = imp->read_name();
3451 imp->require_c_string(" ");
3452 Type* rtype = imp->read_type();
3453 results->push_back(Typed_identifier(name, rtype,
3455 if (imp->peek_char() != ',')
3457 imp->require_c_string(", ");
3459 imp->require_c_string(")");
3462 imp->require_c_string(";\n");
3463 *presults = results;
3468 Block::Block(Block* enclosing, Location location)
3469 : enclosing_(enclosing), statements_(),
3470 bindings_(new Bindings(enclosing == NULL
3472 : enclosing->bindings())),
3473 start_location_(location),
3474 end_location_(UNKNOWN_LOCATION)
3478 // Add a statement to a block.
3481 Block::add_statement(Statement* statement)
3483 this->statements_.push_back(statement);
3486 // Add a statement to the front of a block. This is slow but is only
3487 // used for reference counts of parameters.
3490 Block::add_statement_at_front(Statement* statement)
3492 this->statements_.insert(this->statements_.begin(), statement);
3495 // Replace a statement in a block.
3498 Block::replace_statement(size_t index, Statement* s)
3500 go_assert(index < this->statements_.size());
3501 this->statements_[index] = s;
3504 // Add a statement before another statement.
3507 Block::insert_statement_before(size_t index, Statement* s)
3509 go_assert(index < this->statements_.size());
3510 this->statements_.insert(this->statements_.begin() + index, s);
3513 // Add a statement after another statement.
3516 Block::insert_statement_after(size_t index, Statement* s)
3518 go_assert(index < this->statements_.size());
3519 this->statements_.insert(this->statements_.begin() + index + 1, s);
3522 // Traverse the tree.
3525 Block::traverse(Traverse* traverse)
3527 unsigned int traverse_mask = traverse->traverse_mask();
3529 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3531 int t = traverse->block(this);
3532 if (t == TRAVERSE_EXIT)
3533 return TRAVERSE_EXIT;
3534 else if (t == TRAVERSE_SKIP_COMPONENTS)
3535 return TRAVERSE_CONTINUE;
3539 & (Traverse::traverse_variables
3540 | Traverse::traverse_constants
3541 | Traverse::traverse_expressions
3542 | Traverse::traverse_types)) != 0)
3544 const unsigned int e_or_t = (Traverse::traverse_expressions
3545 | Traverse::traverse_types);
3546 const unsigned int e_or_t_or_s = (e_or_t
3547 | Traverse::traverse_statements);
3548 for (Bindings::const_definitions_iterator pb =
3549 this->bindings_->begin_definitions();
3550 pb != this->bindings_->end_definitions();
3553 int t = TRAVERSE_CONTINUE;
3554 switch ((*pb)->classification())
3556 case Named_object::NAMED_OBJECT_CONST:
3557 if ((traverse_mask & Traverse::traverse_constants) != 0)
3558 t = traverse->constant(*pb, false);
3559 if (t == TRAVERSE_CONTINUE
3560 && (traverse_mask & e_or_t) != 0)
3562 Type* tc = (*pb)->const_value()->type();
3564 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3565 return TRAVERSE_EXIT;
3566 t = (*pb)->const_value()->traverse_expression(traverse);
3570 case Named_object::NAMED_OBJECT_VAR:
3571 case Named_object::NAMED_OBJECT_RESULT_VAR:
3572 if ((traverse_mask & Traverse::traverse_variables) != 0)
3573 t = traverse->variable(*pb);
3574 if (t == TRAVERSE_CONTINUE
3575 && (traverse_mask & e_or_t) != 0)
3577 if ((*pb)->is_result_variable()
3578 || (*pb)->var_value()->has_type())
3580 Type* tv = ((*pb)->is_variable()
3581 ? (*pb)->var_value()->type()
3582 : (*pb)->result_var_value()->type());
3584 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3585 return TRAVERSE_EXIT;
3588 if (t == TRAVERSE_CONTINUE
3589 && (traverse_mask & e_or_t_or_s) != 0
3590 && (*pb)->is_variable())
3591 t = (*pb)->var_value()->traverse_expression(traverse,
3595 case Named_object::NAMED_OBJECT_FUNC:
3596 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3599 case Named_object::NAMED_OBJECT_TYPE:
3600 if ((traverse_mask & e_or_t) != 0)
3601 t = Type::traverse((*pb)->type_value(), traverse);
3604 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3605 case Named_object::NAMED_OBJECT_UNKNOWN:
3606 case Named_object::NAMED_OBJECT_ERRONEOUS:
3609 case Named_object::NAMED_OBJECT_PACKAGE:
3610 case Named_object::NAMED_OBJECT_SINK:
3617 if (t == TRAVERSE_EXIT)
3618 return TRAVERSE_EXIT;
3622 // No point in checking traverse_mask here--if we got here we always
3623 // want to walk the statements. The traversal can insert new
3624 // statements before or after the current statement. Inserting
3625 // statements before the current statement requires updating I via
3626 // the pointer; those statements will not be traversed. Any new
3627 // statements inserted after the current statement will be traversed
3629 for (size_t i = 0; i < this->statements_.size(); ++i)
3631 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3632 return TRAVERSE_EXIT;
3635 return TRAVERSE_CONTINUE;
3638 // Work out types for unspecified variables and constants.
3641 Block::determine_types()
3643 for (Bindings::const_definitions_iterator pb =
3644 this->bindings_->begin_definitions();
3645 pb != this->bindings_->end_definitions();
3648 if ((*pb)->is_variable())
3649 (*pb)->var_value()->determine_type();
3650 else if ((*pb)->is_const())
3651 (*pb)->const_value()->determine_type();
3654 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3655 ps != this->statements_.end();
3657 (*ps)->determine_types();
3660 // Return true if the statements in this block may fall through.
3663 Block::may_fall_through() const
3665 if (this->statements_.empty())
3667 return this->statements_.back()->may_fall_through();
3670 // Convert a block to the backend representation.
3673 Block::get_backend(Translate_context* context)
3675 Gogo* gogo = context->gogo();
3676 Named_object* function = context->function();
3677 std::vector<Bvariable*> vars;
3678 vars.reserve(this->bindings_->size_definitions());
3679 for (Bindings::const_definitions_iterator pv =
3680 this->bindings_->begin_definitions();
3681 pv != this->bindings_->end_definitions();
3684 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
3685 vars.push_back((*pv)->get_backend_variable(gogo, function));
3688 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
3689 // until we have a proper representation of the init function.
3690 Bfunction* bfunction;
3691 if (function == NULL)
3694 bfunction = tree_to_function(function->func_value()->get_decl());
3695 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
3696 vars, this->start_location_,
3697 this->end_location_);
3699 Translate_context subcontext(gogo, function, this, ret);
3700 std::vector<Bstatement*> bstatements;
3701 bstatements.reserve(this->statements_.size());
3702 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
3703 p != this->statements_.end();
3705 bstatements.push_back((*p)->get_backend(&subcontext));
3707 context->backend()->block_add_statements(ret, bstatements);
3712 // Class Bindings_snapshot.
3714 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
3715 : block_(b), counts_(), location_(location)
3719 this->counts_.push_back(b->bindings()->size_definitions());
3724 // Report errors appropriate for a goto from B to this.
3727 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
3730 if (!this->check_goto_block(loc, b, this->block_, &dummy))
3732 this->check_goto_defs(loc, this->block_,
3733 this->block_->bindings()->size_definitions(),
3737 // Report errors appropriate for a goto from this to B.
3740 Bindings_snapshot::check_goto_to(const Block* b)
3743 if (!this->check_goto_block(this->location_, this->block_, b, &index))
3745 this->check_goto_defs(this->location_, b, this->counts_[index],
3746 b->bindings()->size_definitions());
3749 // Report errors appropriate for a goto at LOC from BFROM to BTO.
3750 // Return true if all is well, false if we reported an error. If this
3751 // returns true, it sets *PINDEX to the number of blocks BTO is above
3755 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
3756 const Block* bto, size_t* pindex)
3758 // It is an error if BTO is not either BFROM or above BFROM.
3760 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
3764 error_at(loc, "goto jumps into block");
3765 inform(bto->start_location(), "goto target block starts here");
3773 // Report errors appropriate for a goto at LOC ending at BLOCK, where
3774 // CFROM is the number of names defined at the point of the goto and
3775 // CTO is the number of names defined at the point of the label.
3778 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
3779 size_t cfrom, size_t cto)
3783 Bindings::const_definitions_iterator p =
3784 block->bindings()->begin_definitions();
3785 for (size_t i = 0; i < cfrom; ++i)
3787 go_assert(p != block->bindings()->end_definitions());
3790 go_assert(p != block->bindings()->end_definitions());
3792 std::string n = (*p)->message_name();
3793 error_at(loc, "goto jumps over declaration of %qs", n.c_str());
3794 inform((*p)->location(), "%qs defined here", n.c_str());
3800 Variable::Variable(Type* type, Expression* init, bool is_global,
3801 bool is_parameter, bool is_receiver,
3803 : type_(type), init_(init), preinit_(NULL), location_(location),
3804 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3805 is_receiver_(is_receiver), is_varargs_parameter_(false), is_used_(false),
3806 is_address_taken_(false), is_non_escaping_address_taken_(false),
3807 seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
3808 type_from_range_index_(false), type_from_range_value_(false),
3809 type_from_chan_element_(false), is_type_switch_var_(false),
3810 determined_type_(false)
3812 go_assert(type != NULL || init != NULL);
3813 go_assert(!is_parameter || init == NULL);
3816 // Traverse the initializer expression.
3819 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
3821 if (this->preinit_ != NULL)
3823 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3824 return TRAVERSE_EXIT;
3826 if (this->init_ != NULL
3828 & (Traverse::traverse_expressions | Traverse::traverse_types))
3831 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3832 return TRAVERSE_EXIT;
3834 return TRAVERSE_CONTINUE;
3837 // Lower the initialization expression after parsing is complete.
3840 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
3841 Statement_inserter* inserter)
3843 Named_object* dep = gogo->var_depends_on(this);
3844 if (dep != NULL && dep->is_variable())
3845 dep->var_value()->lower_init_expression(gogo, function, inserter);
3847 if (this->init_ != NULL && !this->init_is_lowered_)
3851 // We will give an error elsewhere, this is just to prevent
3852 // an infinite loop.
3857 Statement_inserter global_inserter;
3858 if (this->is_global_)
3860 global_inserter = Statement_inserter(gogo, this);
3861 inserter = &global_inserter;
3864 gogo->lower_expression(function, inserter, &this->init_);
3866 this->seen_ = false;
3868 this->init_is_lowered_ = true;
3872 // Get the preinit block.
3875 Variable::preinit_block(Gogo* gogo)
3877 go_assert(this->is_global_);
3878 if (this->preinit_ == NULL)
3879 this->preinit_ = new Block(NULL, this->location());
3881 // If a global variable has a preinitialization statement, then we
3882 // need to have an initialization function.
3883 gogo->set_need_init_fn();
3885 return this->preinit_;
3888 // Add a statement to be run before the initialization expression.
3891 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3893 Block* b = this->preinit_block(gogo);
3894 b->add_statement(s);
3895 b->set_end_location(s->location());
3898 // Whether this variable has a type.
3901 Variable::has_type() const
3903 if (this->type_ == NULL)
3906 // A variable created in a type switch case nil does not actually
3907 // have a type yet. It will be changed to use the initializer's
3908 // type in determine_type.
3909 if (this->is_type_switch_var_
3910 && this->type_->is_nil_constant_as_type())
3916 // In an assignment which sets a variable to a tuple of EXPR, return
3917 // the type of the first element of the tuple.
3920 Variable::type_from_tuple(Expression* expr, bool report_error) const
3922 if (expr->map_index_expression() != NULL)
3924 Map_type* mt = expr->map_index_expression()->get_map_type();
3926 return Type::make_error_type();
3927 return mt->val_type();
3929 else if (expr->receive_expression() != NULL)
3931 Expression* channel = expr->receive_expression()->channel();
3932 Type* channel_type = channel->type();
3933 if (channel_type->channel_type() == NULL)
3934 return Type::make_error_type();
3935 return channel_type->channel_type()->element_type();
3940 error_at(this->location(), "invalid tuple definition");
3941 return Type::make_error_type();
3945 // Given EXPR used in a range clause, return either the index type or
3946 // the value type of the range, depending upon GET_INDEX_TYPE.
3949 Variable::type_from_range(Expression* expr, bool get_index_type,
3950 bool report_error) const
3952 Type* t = expr->type();
3953 if (t->array_type() != NULL
3954 || (t->points_to() != NULL
3955 && t->points_to()->array_type() != NULL
3956 && !t->points_to()->is_slice_type()))
3959 return Type::lookup_integer_type("int");
3961 return t->deref()->array_type()->element_type();
3963 else if (t->is_string_type())
3966 return Type::lookup_integer_type("int");
3968 return Type::lookup_integer_type("int32");
3970 else if (t->map_type() != NULL)
3973 return t->map_type()->key_type();
3975 return t->map_type()->val_type();
3977 else if (t->channel_type() != NULL)
3980 return t->channel_type()->element_type();
3984 error_at(this->location(),
3985 "invalid definition of value variable for channel range");
3986 return Type::make_error_type();
3992 error_at(this->location(), "invalid type for range clause");
3993 return Type::make_error_type();
3997 // EXPR should be a channel. Return the channel's element type.
4000 Variable::type_from_chan_element(Expression* expr, bool report_error) const
4002 Type* t = expr->type();
4003 if (t->channel_type() != NULL)
4004 return t->channel_type()->element_type();
4008 error_at(this->location(), "expected channel");
4009 return Type::make_error_type();
4013 // Return the type of the Variable. This may be called before
4014 // Variable::determine_type is called, which means that we may need to
4015 // get the type from the initializer. FIXME: If we combine lowering
4016 // with type determination, then this should be unnecessary.
4021 // A variable in a type switch with a nil case will have the wrong
4022 // type here. This gets fixed up in determine_type, below.
4023 Type* type = this->type_;
4024 Expression* init = this->init_;
4025 if (this->is_type_switch_var_
4026 && this->type_->is_nil_constant_as_type())
4028 Type_guard_expression* tge = this->init_->type_guard_expression();
4029 go_assert(tge != NULL);
4036 if (this->type_ == NULL || !this->type_->is_error_type())
4038 error_at(this->location_, "variable initializer refers to itself");
4039 this->type_ = Type::make_error_type();
4048 else if (this->type_from_init_tuple_)
4049 type = this->type_from_tuple(init, false);
4050 else if (this->type_from_range_index_ || this->type_from_range_value_)
4051 type = this->type_from_range(init, this->type_from_range_index_, false);
4052 else if (this->type_from_chan_element_)
4053 type = this->type_from_chan_element(init, false);
4056 go_assert(init != NULL);
4057 type = init->type();
4058 go_assert(type != NULL);
4060 // Variables should not have abstract types.
4061 if (type->is_abstract())
4062 type = type->make_non_abstract_type();
4064 if (type->is_void_type())
4065 type = Type::make_error_type();
4068 this->seen_ = false;
4073 // Fetch the type from a const pointer, in which case it should have
4074 // been set already.
4077 Variable::type() const
4079 go_assert(this->type_ != NULL);
4083 // Set the type if necessary.
4086 Variable::determine_type()
4088 if (this->determined_type_)
4090 this->determined_type_ = true;
4092 if (this->preinit_ != NULL)
4093 this->preinit_->determine_types();
4095 // A variable in a type switch with a nil case will have the wrong
4096 // type here. It will have an initializer which is a type guard.
4097 // We want to initialize it to the value without the type guard, and
4098 // use the type of that value as well.
4099 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
4101 Type_guard_expression* tge = this->init_->type_guard_expression();
4102 go_assert(tge != NULL);
4104 this->init_ = tge->expr();
4107 if (this->init_ == NULL)
4108 go_assert(this->type_ != NULL && !this->type_->is_abstract());
4109 else if (this->type_from_init_tuple_)
4111 Expression *init = this->init_;
4112 init->determine_type_no_context();
4113 this->type_ = this->type_from_tuple(init, true);
4116 else if (this->type_from_range_index_ || this->type_from_range_value_)
4118 Expression* init = this->init_;
4119 init->determine_type_no_context();
4120 this->type_ = this->type_from_range(init, this->type_from_range_index_,
4124 else if (this->type_from_chan_element_)
4126 Expression* init = this->init_;
4127 init->determine_type_no_context();
4128 this->type_ = this->type_from_chan_element(init, true);
4133 Type_context context(this->type_, false);
4134 this->init_->determine_type(&context);
4135 if (this->type_ == NULL)
4137 Type* type = this->init_->type();
4138 go_assert(type != NULL);
4139 if (type->is_abstract())
4140 type = type->make_non_abstract_type();
4142 if (type->is_void_type())
4144 error_at(this->location_, "variable has no type");
4145 type = Type::make_error_type();
4147 else if (type->is_nil_type())
4149 error_at(this->location_, "variable defined to nil type");
4150 type = Type::make_error_type();
4152 else if (type->is_call_multiple_result_type())
4154 error_at(this->location_,
4155 "single variable set to multiple value function call");
4156 type = Type::make_error_type();
4164 // Export the variable
4167 Variable::export_var(Export* exp, const std::string& name) const
4169 go_assert(this->is_global_);
4170 exp->write_c_string("var ");
4171 exp->write_string(name);
4172 exp->write_c_string(" ");
4173 exp->write_type(this->type());
4174 exp->write_c_string(";\n");
4177 // Import a variable.
4180 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
4182 imp->require_c_string("var ");
4183 *pname = imp->read_identifier();
4184 imp->require_c_string(" ");
4185 *ptype = imp->read_type();
4186 imp->require_c_string(";\n");
4189 // Convert a variable to the backend representation.
4192 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
4193 const Package* package, const std::string& name)
4195 if (this->backend_ == NULL)
4197 Backend* backend = gogo->backend();
4198 Type* type = this->type_;
4199 if (type->is_error_type()
4200 || (type->is_undefined()
4201 && (!this->is_global_ || package == NULL)))
4202 this->backend_ = backend->error_variable();
4205 bool is_parameter = this->is_parameter_;
4206 if (this->is_receiver_ && type->points_to() == NULL)
4207 is_parameter = false;
4208 if (this->is_in_heap())
4210 is_parameter = false;
4211 type = Type::make_pointer_type(type);
4214 std::string n = Gogo::unpack_hidden_name(name);
4215 Btype* btype = type->get_backend(gogo);
4218 if (this->is_global_)
4219 bvar = backend->global_variable((package == NULL
4220 ? gogo->package_name()
4221 : package->package_name()),
4223 ? gogo->pkgpath_symbol()
4224 : package->pkgpath_symbol()),
4228 Gogo::is_hidden_name(name),
4230 else if (function == NULL)
4232 go_assert(saw_errors());
4233 bvar = backend->error_variable();
4237 tree fndecl = function->func_value()->get_decl();
4238 Bfunction* bfunction = tree_to_function(fndecl);
4239 bool is_address_taken = (this->is_non_escaping_address_taken_
4240 && !this->is_in_heap());
4242 bvar = backend->parameter_variable(bfunction, n, btype,
4246 bvar = backend->local_variable(bfunction, n, btype,
4250 this->backend_ = bvar;
4253 return this->backend_;
4256 // Class Result_variable.
4258 // Convert a result variable to the backend representation.
4261 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
4262 const std::string& name)
4264 if (this->backend_ == NULL)
4266 Backend* backend = gogo->backend();
4267 Type* type = this->type_;
4268 if (type->is_error())
4269 this->backend_ = backend->error_variable();
4272 if (this->is_in_heap())
4273 type = Type::make_pointer_type(type);
4274 Btype* btype = type->get_backend(gogo);
4275 tree fndecl = function->func_value()->get_decl();
4276 Bfunction* bfunction = tree_to_function(fndecl);
4277 std::string n = Gogo::unpack_hidden_name(name);
4278 bool is_address_taken = (this->is_non_escaping_address_taken_
4279 && !this->is_in_heap());
4280 this->backend_ = backend->local_variable(bfunction, n, btype,
4285 return this->backend_;
4288 // Class Named_constant.
4290 // Traverse the initializer expression.
4293 Named_constant::traverse_expression(Traverse* traverse)
4295 return Expression::traverse(&this->expr_, traverse);
4298 // Determine the type of the constant.
4301 Named_constant::determine_type()
4303 if (this->type_ != NULL)
4305 Type_context context(this->type_, false);
4306 this->expr_->determine_type(&context);
4310 // A constant may have an abstract type.
4311 Type_context context(NULL, true);
4312 this->expr_->determine_type(&context);
4313 this->type_ = this->expr_->type();
4314 go_assert(this->type_ != NULL);
4318 // Indicate that we found and reported an error for this constant.
4321 Named_constant::set_error()
4323 this->type_ = Type::make_error_type();
4324 this->expr_ = Expression::make_error(this->location_);
4327 // Export a constant.
4330 Named_constant::export_const(Export* exp, const std::string& name) const
4332 exp->write_c_string("const ");
4333 exp->write_string(name);
4334 exp->write_c_string(" ");
4335 if (!this->type_->is_abstract())
4337 exp->write_type(this->type_);
4338 exp->write_c_string(" ");
4340 exp->write_c_string("= ");
4341 this->expr()->export_expression(exp);
4342 exp->write_c_string(";\n");
4345 // Import a constant.
4348 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
4351 imp->require_c_string("const ");
4352 *pname = imp->read_identifier();
4353 imp->require_c_string(" ");
4354 if (imp->peek_char() == '=')
4358 *ptype = imp->read_type();
4359 imp->require_c_string(" ");
4361 imp->require_c_string("= ");
4362 *pexpr = Expression::import_expression(imp);
4363 imp->require_c_string(";\n");
4369 Type_declaration::add_method(const std::string& name, Function* function)
4371 Named_object* ret = Named_object::make_function(name, NULL, function);
4372 this->methods_.push_back(ret);
4376 // Add a method declaration.
4379 Type_declaration::add_method_declaration(const std::string& name,
4381 Function_type* type,
4384 Named_object* ret = Named_object::make_function_declaration(name, package,
4386 this->methods_.push_back(ret);
4390 // Return whether any methods ere defined.
4393 Type_declaration::has_methods() const
4395 return !this->methods_.empty();
4398 // Define methods for the real type.
4401 Type_declaration::define_methods(Named_type* nt)
4403 for (Methods::const_iterator p = this->methods_.begin();
4404 p != this->methods_.end();
4406 nt->add_existing_method(*p);
4409 // We are using the type. Return true if we should issue a warning.
4412 Type_declaration::using_type()
4414 bool ret = !this->issued_warning_;
4415 this->issued_warning_ = true;
4419 // Class Unknown_name.
4421 // Set the real named object.
4424 Unknown_name::set_real_named_object(Named_object* no)
4426 go_assert(this->real_named_object_ == NULL);
4427 go_assert(!no->is_unknown());
4428 this->real_named_object_ = no;
4431 // Class Named_object.
4433 Named_object::Named_object(const std::string& name,
4434 const Package* package,
4435 Classification classification)
4436 : name_(name), package_(package), classification_(classification),
4439 if (Gogo::is_sink_name(name))
4440 go_assert(classification == NAMED_OBJECT_SINK);
4443 // Make an unknown name. This is used by the parser. The name must
4444 // be resolved later. Unknown names are only added in the current
4448 Named_object::make_unknown_name(const std::string& name,
4451 Named_object* named_object = new Named_object(name, NULL,
4452 NAMED_OBJECT_UNKNOWN);
4453 Unknown_name* value = new Unknown_name(location);
4454 named_object->u_.unknown_value = value;
4455 return named_object;
4461 Named_object::make_constant(const Typed_identifier& tid,
4462 const Package* package, Expression* expr,
4465 Named_object* named_object = new Named_object(tid.name(), package,
4466 NAMED_OBJECT_CONST);
4467 Named_constant* named_constant = new Named_constant(tid.type(), expr,
4470 named_object->u_.const_value = named_constant;
4471 return named_object;
4474 // Make a named type.
4477 Named_object::make_type(const std::string& name, const Package* package,
4478 Type* type, Location location)
4480 Named_object* named_object = new Named_object(name, package,
4482 Named_type* named_type = Type::make_named_type(named_object, type, location);
4483 named_object->u_.type_value = named_type;
4484 return named_object;
4487 // Make a type declaration.
4490 Named_object::make_type_declaration(const std::string& name,
4491 const Package* package,
4494 Named_object* named_object = new Named_object(name, package,
4495 NAMED_OBJECT_TYPE_DECLARATION);
4496 Type_declaration* type_declaration = new Type_declaration(location);
4497 named_object->u_.type_declaration = type_declaration;
4498 return named_object;
4504 Named_object::make_variable(const std::string& name, const Package* package,
4507 Named_object* named_object = new Named_object(name, package,
4509 named_object->u_.var_value = variable;
4510 return named_object;
4513 // Make a result variable.
4516 Named_object::make_result_variable(const std::string& name,
4517 Result_variable* result)
4519 Named_object* named_object = new Named_object(name, NULL,
4520 NAMED_OBJECT_RESULT_VAR);
4521 named_object->u_.result_var_value = result;
4522 return named_object;
4525 // Make a sink. This is used for the special blank identifier _.
4528 Named_object::make_sink()
4530 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4533 // Make a named function.
4536 Named_object::make_function(const std::string& name, const Package* package,
4539 Named_object* named_object = new Named_object(name, package,
4541 named_object->u_.func_value = function;
4542 return named_object;
4545 // Make a function declaration.
4548 Named_object::make_function_declaration(const std::string& name,
4549 const Package* package,
4550 Function_type* fntype,
4553 Named_object* named_object = new Named_object(name, package,
4554 NAMED_OBJECT_FUNC_DECLARATION);
4555 Function_declaration *func_decl = new Function_declaration(fntype, location);
4556 named_object->u_.func_declaration_value = func_decl;
4557 return named_object;
4563 Named_object::make_package(const std::string& alias, Package* package)
4565 Named_object* named_object = new Named_object(alias, NULL,
4566 NAMED_OBJECT_PACKAGE);
4567 named_object->u_.package_value = package;
4568 return named_object;
4571 // Return the name to use in an error message.
4574 Named_object::message_name() const
4576 if (this->package_ == NULL)
4577 return Gogo::message_name(this->name_);
4579 if (this->package_->has_package_name())
4580 ret = this->package_->package_name();
4582 ret = this->package_->pkgpath();
4583 ret = Gogo::message_name(ret);
4585 ret += Gogo::message_name(this->name_);
4589 // Set the type when a declaration is defined.
4592 Named_object::set_type_value(Named_type* named_type)
4594 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4595 Type_declaration* td = this->u_.type_declaration;
4596 td->define_methods(named_type);
4597 Named_object* in_function = td->in_function();
4598 if (in_function != NULL)
4599 named_type->set_in_function(in_function);
4601 this->classification_ = NAMED_OBJECT_TYPE;
4602 this->u_.type_value = named_type;
4605 // Define a function which was previously declared.
4608 Named_object::set_function_value(Function* function)
4610 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4611 this->classification_ = NAMED_OBJECT_FUNC;
4612 // FIXME: We should free the old value.
4613 this->u_.func_value = function;
4616 // Declare an unknown object as a type declaration.
4619 Named_object::declare_as_type()
4621 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4622 Unknown_name* unk = this->u_.unknown_value;
4623 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
4624 this->u_.type_declaration = new Type_declaration(unk->location());
4628 // Return the location of a named object.
4631 Named_object::location() const
4633 switch (this->classification_)
4636 case NAMED_OBJECT_UNINITIALIZED:
4639 case NAMED_OBJECT_ERRONEOUS:
4640 return Linemap::unknown_location();
4642 case NAMED_OBJECT_UNKNOWN:
4643 return this->unknown_value()->location();
4645 case NAMED_OBJECT_CONST:
4646 return this->const_value()->location();
4648 case NAMED_OBJECT_TYPE:
4649 return this->type_value()->location();
4651 case NAMED_OBJECT_TYPE_DECLARATION:
4652 return this->type_declaration_value()->location();
4654 case NAMED_OBJECT_VAR:
4655 return this->var_value()->location();
4657 case NAMED_OBJECT_RESULT_VAR:
4658 return this->result_var_value()->location();
4660 case NAMED_OBJECT_SINK:
4663 case NAMED_OBJECT_FUNC:
4664 return this->func_value()->location();
4666 case NAMED_OBJECT_FUNC_DECLARATION:
4667 return this->func_declaration_value()->location();
4669 case NAMED_OBJECT_PACKAGE:
4670 return this->package_value()->location();
4674 // Export a named object.
4677 Named_object::export_named_object(Export* exp) const
4679 switch (this->classification_)
4682 case NAMED_OBJECT_UNINITIALIZED:
4683 case NAMED_OBJECT_UNKNOWN:
4686 case NAMED_OBJECT_ERRONEOUS:
4689 case NAMED_OBJECT_CONST:
4690 this->const_value()->export_const(exp, this->name_);
4693 case NAMED_OBJECT_TYPE:
4694 this->type_value()->export_named_type(exp, this->name_);
4697 case NAMED_OBJECT_TYPE_DECLARATION:
4698 error_at(this->type_declaration_value()->location(),
4699 "attempt to export %<%s%> which was declared but not defined",
4700 this->message_name().c_str());
4703 case NAMED_OBJECT_FUNC_DECLARATION:
4704 this->func_declaration_value()->export_func(exp, this->name_);
4707 case NAMED_OBJECT_VAR:
4708 this->var_value()->export_var(exp, this->name_);
4711 case NAMED_OBJECT_RESULT_VAR:
4712 case NAMED_OBJECT_SINK:
4715 case NAMED_OBJECT_FUNC:
4716 this->func_value()->export_func(exp, this->name_);
4721 // Convert a variable to the backend representation.
4724 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
4726 if (this->classification_ == NAMED_OBJECT_VAR)
4727 return this->var_value()->get_backend_variable(gogo, function,
4728 this->package_, this->name_);
4729 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
4730 return this->result_var_value()->get_backend_variable(gogo, function,
4738 Bindings::Bindings(Bindings* enclosing)
4739 : enclosing_(enclosing), named_objects_(), bindings_()
4746 Bindings::clear_file_scope()
4748 Contour::iterator p = this->bindings_.begin();
4749 while (p != this->bindings_.end())
4752 if (p->second->package() != NULL)
4754 else if (p->second->is_package())
4756 else if (p->second->is_function()
4757 && !p->second->func_value()->type()->is_method()
4758 && Gogo::unpack_hidden_name(p->second->name()) == "init")
4766 p = this->bindings_.erase(p);
4770 // Look up a symbol.
4773 Bindings::lookup(const std::string& name) const
4775 Contour::const_iterator p = this->bindings_.find(name);
4776 if (p != this->bindings_.end())
4777 return p->second->resolve();
4778 else if (this->enclosing_ != NULL)
4779 return this->enclosing_->lookup(name);
4784 // Look up a symbol locally.
4787 Bindings::lookup_local(const std::string& name) const
4789 Contour::const_iterator p = this->bindings_.find(name);
4790 if (p == this->bindings_.end())
4795 // Remove an object from a set of bindings. This is used for a
4796 // special case in thunks for functions which call recover.
4799 Bindings::remove_binding(Named_object* no)
4801 Contour::iterator pb = this->bindings_.find(no->name());
4802 go_assert(pb != this->bindings_.end());
4803 this->bindings_.erase(pb);
4804 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4805 pn != this->named_objects_.end();
4810 this->named_objects_.erase(pn);
4817 // Add a method to the list of objects. This is not added to the
4818 // lookup table. This is so that we have a single list of objects
4819 // declared at the top level, which we walk through when it's time to
4820 // convert to trees.
4823 Bindings::add_method(Named_object* method)
4825 this->named_objects_.push_back(method);
4828 // Add a generic Named_object to a Contour.
4831 Bindings::add_named_object_to_contour(Contour* contour,
4832 Named_object* named_object)
4834 go_assert(named_object == named_object->resolve());
4835 const std::string& name(named_object->name());
4836 go_assert(!Gogo::is_sink_name(name));
4838 std::pair<Contour::iterator, bool> ins =
4839 contour->insert(std::make_pair(name, named_object));
4842 // The name was already there.
4843 if (named_object->package() != NULL
4844 && ins.first->second->package() == named_object->package()
4845 && (ins.first->second->classification()
4846 == named_object->classification()))
4848 // This is a second import of the same object.
4849 return ins.first->second;
4851 ins.first->second = this->new_definition(ins.first->second,
4853 return ins.first->second;
4857 // Don't push declarations on the list. We push them on when
4858 // and if we find the definitions. That way we genericize the
4859 // functions in order.
4860 if (!named_object->is_type_declaration()
4861 && !named_object->is_function_declaration()
4862 && !named_object->is_unknown())
4863 this->named_objects_.push_back(named_object);
4864 return named_object;
4868 // We had an existing named object OLD_OBJECT, and we've seen a new
4869 // one NEW_OBJECT with the same name. FIXME: This does not free the
4870 // new object when we don't need it.
4873 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4875 if (new_object->is_erroneous() && !old_object->is_erroneous())
4879 switch (old_object->classification())
4882 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4885 case Named_object::NAMED_OBJECT_ERRONEOUS:
4888 case Named_object::NAMED_OBJECT_UNKNOWN:
4890 Named_object* real = old_object->unknown_value()->real_named_object();
4892 return this->new_definition(real, new_object);
4893 go_assert(!new_object->is_unknown());
4894 old_object->unknown_value()->set_real_named_object(new_object);
4895 if (!new_object->is_type_declaration()
4896 && !new_object->is_function_declaration())
4897 this->named_objects_.push_back(new_object);
4901 case Named_object::NAMED_OBJECT_CONST:
4904 case Named_object::NAMED_OBJECT_TYPE:
4905 if (new_object->is_type_declaration())
4909 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4910 if (new_object->is_type_declaration())
4912 if (new_object->is_type())
4914 old_object->set_type_value(new_object->type_value());
4915 new_object->type_value()->set_named_object(old_object);
4916 this->named_objects_.push_back(old_object);
4921 case Named_object::NAMED_OBJECT_VAR:
4922 case Named_object::NAMED_OBJECT_RESULT_VAR:
4923 // We have already given an error in the parser for cases where
4924 // one parameter or result variable redeclares another one.
4925 if ((new_object->is_variable()
4926 && new_object->var_value()->is_parameter())
4927 || new_object->is_result_variable())
4931 case Named_object::NAMED_OBJECT_SINK:
4934 case Named_object::NAMED_OBJECT_FUNC:
4935 if (new_object->is_function_declaration())
4937 if (!new_object->func_declaration_value()->asm_name().empty())
4938 sorry("__asm__ for function definitions");
4939 Function_type* old_type = old_object->func_value()->type();
4940 Function_type* new_type =
4941 new_object->func_declaration_value()->type();
4942 if (old_type->is_valid_redeclaration(new_type, &reason))
4947 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4949 Function_type* old_type = old_object->func_declaration_value()->type();
4950 if (new_object->is_function_declaration())
4952 Function_type* new_type =
4953 new_object->func_declaration_value()->type();
4954 if (old_type->is_valid_redeclaration(new_type, &reason))
4957 if (new_object->is_function())
4959 Function_type* new_type = new_object->func_value()->type();
4960 if (old_type->is_valid_redeclaration(new_type, &reason))
4962 if (!old_object->func_declaration_value()->asm_name().empty())
4963 sorry("__asm__ for function definitions");
4964 old_object->set_function_value(new_object->func_value());
4965 this->named_objects_.push_back(old_object);
4972 case Named_object::NAMED_OBJECT_PACKAGE:
4976 std::string n = old_object->message_name();
4978 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4980 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4983 inform(old_object->location(), "previous definition of %qs was here",
4989 // Add a named type.
4992 Bindings::add_named_type(Named_type* named_type)
4994 return this->add_named_object(named_type->named_object());
5000 Bindings::add_function(const std::string& name, const Package* package,
5003 return this->add_named_object(Named_object::make_function(name, package,
5007 // Add a function declaration.
5010 Bindings::add_function_declaration(const std::string& name,
5011 const Package* package,
5012 Function_type* type,
5015 Named_object* no = Named_object::make_function_declaration(name, package,
5017 return this->add_named_object(no);
5020 // Define a type which was previously declared.
5023 Bindings::define_type(Named_object* no, Named_type* type)
5025 no->set_type_value(type);
5026 this->named_objects_.push_back(no);
5029 // Mark all local variables as used. This is used for some types of
5033 Bindings::mark_locals_used()
5035 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
5036 p != this->named_objects_.end();
5038 if ((*p)->is_variable())
5039 (*p)->var_value()->set_is_used();
5042 // Traverse bindings.
5045 Bindings::traverse(Traverse* traverse, bool is_global)
5047 unsigned int traverse_mask = traverse->traverse_mask();
5049 // We don't use an iterator because we permit the traversal to add
5050 // new global objects.
5051 const unsigned int e_or_t = (Traverse::traverse_expressions
5052 | Traverse::traverse_types);
5053 const unsigned int e_or_t_or_s = (e_or_t
5054 | Traverse::traverse_statements);
5055 for (size_t i = 0; i < this->named_objects_.size(); ++i)
5057 Named_object* p = this->named_objects_[i];
5058 int t = TRAVERSE_CONTINUE;
5059 switch (p->classification())
5061 case Named_object::NAMED_OBJECT_CONST:
5062 if ((traverse_mask & Traverse::traverse_constants) != 0)
5063 t = traverse->constant(p, is_global);
5064 if (t == TRAVERSE_CONTINUE
5065 && (traverse_mask & e_or_t) != 0)
5067 Type* tc = p->const_value()->type();
5069 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5070 return TRAVERSE_EXIT;
5071 t = p->const_value()->traverse_expression(traverse);
5075 case Named_object::NAMED_OBJECT_VAR:
5076 case Named_object::NAMED_OBJECT_RESULT_VAR:
5077 if ((traverse_mask & Traverse::traverse_variables) != 0)
5078 t = traverse->variable(p);
5079 if (t == TRAVERSE_CONTINUE
5080 && (traverse_mask & e_or_t) != 0)
5082 if (p->is_result_variable()
5083 || p->var_value()->has_type())
5085 Type* tv = (p->is_variable()
5086 ? p->var_value()->type()
5087 : p->result_var_value()->type());
5089 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5090 return TRAVERSE_EXIT;
5093 if (t == TRAVERSE_CONTINUE
5094 && (traverse_mask & e_or_t_or_s) != 0
5095 && p->is_variable())
5096 t = p->var_value()->traverse_expression(traverse, traverse_mask);
5099 case Named_object::NAMED_OBJECT_FUNC:
5100 if ((traverse_mask & Traverse::traverse_functions) != 0)
5101 t = traverse->function(p);
5103 if (t == TRAVERSE_CONTINUE
5105 & (Traverse::traverse_variables
5106 | Traverse::traverse_constants
5107 | Traverse::traverse_functions
5108 | Traverse::traverse_blocks
5109 | Traverse::traverse_statements
5110 | Traverse::traverse_expressions
5111 | Traverse::traverse_types)) != 0)
5112 t = p->func_value()->traverse(traverse);
5115 case Named_object::NAMED_OBJECT_PACKAGE:
5116 // These are traversed in Gogo::traverse.
5117 go_assert(is_global);
5120 case Named_object::NAMED_OBJECT_TYPE:
5121 if ((traverse_mask & e_or_t) != 0)
5122 t = Type::traverse(p->type_value(), traverse);
5125 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5126 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5127 case Named_object::NAMED_OBJECT_UNKNOWN:
5128 case Named_object::NAMED_OBJECT_ERRONEOUS:
5131 case Named_object::NAMED_OBJECT_SINK:
5136 if (t == TRAVERSE_EXIT)
5137 return TRAVERSE_EXIT;
5140 // If we need to traverse types, check the function declarations,
5141 // which have types. We don't need to check the type declarations,
5142 // as those are just names.
5143 if ((traverse_mask & e_or_t) != 0)
5145 for (Bindings::const_declarations_iterator p =
5146 this->begin_declarations();
5147 p != this->end_declarations();
5150 if (p->second->is_function_declaration())
5152 if (Type::traverse(p->second->func_declaration_value()->type(),
5155 return TRAVERSE_EXIT;
5160 return TRAVERSE_CONTINUE;
5165 // Clear any references to this label.
5170 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
5171 p != this->refs_.end();
5174 this->refs_.clear();
5177 // Get the backend representation for a label.
5180 Label::get_backend_label(Translate_context* context)
5182 if (this->blabel_ == NULL)
5184 Function* function = context->function()->func_value();
5185 tree fndecl = function->get_decl();
5186 Bfunction* bfunction = tree_to_function(fndecl);
5187 this->blabel_ = context->backend()->label(bfunction, this->name_,
5190 return this->blabel_;
5193 // Return an expression for the address of this label.
5196 Label::get_addr(Translate_context* context, Location location)
5198 Blabel* label = this->get_backend_label(context);
5199 return context->backend()->label_address(label, location);
5202 // Class Unnamed_label.
5204 // Get the backend representation for an unnamed label.
5207 Unnamed_label::get_blabel(Translate_context* context)
5209 if (this->blabel_ == NULL)
5211 Function* function = context->function()->func_value();
5212 tree fndecl = function->get_decl();
5213 Bfunction* bfunction = tree_to_function(fndecl);
5214 this->blabel_ = context->backend()->label(bfunction, "",
5217 return this->blabel_;
5220 // Return a statement which defines this unnamed label.
5223 Unnamed_label::get_definition(Translate_context* context)
5225 Blabel* blabel = this->get_blabel(context);
5226 return context->backend()->label_definition_statement(blabel);
5229 // Return a goto statement to this unnamed label.
5232 Unnamed_label::get_goto(Translate_context* context, Location location)
5234 Blabel* blabel = this->get_blabel(context);
5235 return context->backend()->goto_statement(blabel, location);
5240 Package::Package(const std::string& pkgpath, Location location)
5241 : pkgpath_(pkgpath), pkgpath_symbol_(Gogo::pkgpath_for_symbol(pkgpath)),
5242 package_name_(), bindings_(new Bindings(NULL)), priority_(0),
5243 location_(location), used_(false), is_imported_(false),
5244 uses_sink_alias_(false)
5246 go_assert(!pkgpath.empty());
5250 // Set the package name.
5253 Package::set_package_name(const std::string& package_name, Location location)
5255 go_assert(!package_name.empty());
5256 if (this->package_name_.empty())
5257 this->package_name_ = package_name;
5258 else if (this->package_name_ != package_name)
5260 "saw two different packages with the same package path %s: %s, %s",
5261 this->pkgpath_.c_str(), this->package_name_.c_str(),
5262 package_name.c_str());
5265 // Set the priority. We may see multiple priorities for an imported
5266 // package; we want to use the largest one.
5269 Package::set_priority(int priority)
5271 if (priority > this->priority_)
5272 this->priority_ = priority;
5275 // Determine types of constants. Everything else in a package
5276 // (variables, function declarations) should already have a fixed
5277 // type. Constants may have abstract types.
5280 Package::determine_types()
5282 Bindings* bindings = this->bindings_;
5283 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5284 p != bindings->end_definitions();
5287 if ((*p)->is_const())
5288 (*p)->const_value()->determine_type();
5296 Traverse::~Traverse()
5298 if (this->types_seen_ != NULL)
5299 delete this->types_seen_;
5300 if (this->expressions_seen_ != NULL)
5301 delete this->expressions_seen_;
5304 // Record that we are looking at a type, and return true if we have
5308 Traverse::remember_type(const Type* type)
5310 if (type->is_error_type())
5312 go_assert((this->traverse_mask() & traverse_types) != 0
5313 || (this->traverse_mask() & traverse_expressions) != 0);
5314 // We mostly only have to remember named types. But it turns out
5315 // that an interface type can refer to itself without using a name
5316 // by relying on interface inheritance, as in
5317 // type I interface { F() interface{I} }
5318 if (type->classification() != Type::TYPE_NAMED
5319 && type->classification() != Type::TYPE_INTERFACE)
5321 if (this->types_seen_ == NULL)
5322 this->types_seen_ = new Types_seen();
5323 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
5327 // Record that we are looking at an expression, and return true if we
5328 // have already seen it.
5331 Traverse::remember_expression(const Expression* expression)
5333 go_assert((this->traverse_mask() & traverse_types) != 0
5334 || (this->traverse_mask() & traverse_expressions) != 0);
5335 if (this->expressions_seen_ == NULL)
5336 this->expressions_seen_ = new Expressions_seen();
5337 std::pair<Expressions_seen::iterator, bool> ins =
5338 this->expressions_seen_->insert(expression);
5342 // The default versions of these functions should never be called: the
5343 // traversal mask indicates which functions may be called.
5346 Traverse::variable(Named_object*)
5352 Traverse::constant(Named_object*, bool)
5358 Traverse::function(Named_object*)
5364 Traverse::block(Block*)
5370 Traverse::statement(Block*, size_t*, Statement*)
5376 Traverse::expression(Expression**)
5382 Traverse::type(Type*)
5387 // Class Statement_inserter.
5390 Statement_inserter::insert(Statement* s)
5392 if (this->block_ != NULL)
5394 go_assert(this->pindex_ != NULL);
5395 this->block_->insert_statement_before(*this->pindex_, s);
5398 else if (this->var_ != NULL)
5399 this->var_->add_preinit_statement(this->gogo_, s);
5401 go_assert(saw_errors());