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"
22 Gogo::Gogo(int int_type_size, int pointer_size)
25 globals_(new Bindings(NULL)),
27 imported_unsafe_(false),
29 map_descriptors_(NULL),
30 type_descriptor_decls_(NULL),
36 unique_prefix_specified_(false),
39 const source_location loc = BUILTINS_LOCATION;
41 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
42 RUNTIME_TYPE_KIND_UINT8);
43 this->add_named_type(uint8_type);
44 this->add_named_type(Type::make_integer_type("uint16", true, 16,
45 RUNTIME_TYPE_KIND_UINT16));
46 this->add_named_type(Type::make_integer_type("uint32", true, 32,
47 RUNTIME_TYPE_KIND_UINT32));
48 this->add_named_type(Type::make_integer_type("uint64", true, 64,
49 RUNTIME_TYPE_KIND_UINT64));
51 this->add_named_type(Type::make_integer_type("int8", false, 8,
52 RUNTIME_TYPE_KIND_INT8));
53 this->add_named_type(Type::make_integer_type("int16", false, 16,
54 RUNTIME_TYPE_KIND_INT16));
55 this->add_named_type(Type::make_integer_type("int32", false, 32,
56 RUNTIME_TYPE_KIND_INT32));
57 this->add_named_type(Type::make_integer_type("int64", false, 64,
58 RUNTIME_TYPE_KIND_INT64));
60 this->add_named_type(Type::make_float_type("float32", 32,
61 RUNTIME_TYPE_KIND_FLOAT32));
62 this->add_named_type(Type::make_float_type("float64", 64,
63 RUNTIME_TYPE_KIND_FLOAT64));
65 this->add_named_type(Type::make_complex_type("complex64", 64,
66 RUNTIME_TYPE_KIND_COMPLEX64));
67 this->add_named_type(Type::make_complex_type("complex128", 128,
68 RUNTIME_TYPE_KIND_COMPLEX128));
70 if (int_type_size < 32)
72 this->add_named_type(Type::make_integer_type("uint", true,
74 RUNTIME_TYPE_KIND_UINT));
75 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
76 RUNTIME_TYPE_KIND_INT);
77 this->add_named_type(int_type);
79 // "byte" is an alias for "uint8". Construct a Named_object which
80 // points to UINT8_TYPE. Note that this breaks the normal pairing
81 // in which a Named_object points to a Named_type which points back
82 // to the same Named_object.
83 Named_object* byte_type = this->declare_type("byte", loc);
84 byte_type->set_type_value(uint8_type);
86 this->add_named_type(Type::make_integer_type("uintptr", true,
88 RUNTIME_TYPE_KIND_UINTPTR));
90 this->add_named_type(Type::make_named_bool_type());
92 this->add_named_type(Type::make_named_string_type());
94 this->globals_->add_constant(Typed_identifier("true",
95 Type::make_boolean_type(),
98 Expression::make_boolean(true, loc),
100 this->globals_->add_constant(Typed_identifier("false",
101 Type::make_boolean_type(),
104 Expression::make_boolean(false, loc),
107 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
110 Expression::make_nil(loc),
113 Type* abstract_int_type = Type::make_abstract_integer_type();
114 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
117 Expression::make_iota(),
120 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
121 new_type->set_is_varargs();
122 new_type->set_is_builtin();
123 this->globals_->add_function_declaration("new", NULL, new_type, loc);
125 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
126 make_type->set_is_varargs();
127 make_type->set_is_builtin();
128 this->globals_->add_function_declaration("make", NULL, make_type, loc);
130 Typed_identifier_list* len_result = new Typed_identifier_list();
131 len_result->push_back(Typed_identifier("", int_type, loc));
132 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
134 len_type->set_is_builtin();
135 this->globals_->add_function_declaration("len", NULL, len_type, loc);
137 Typed_identifier_list* cap_result = new Typed_identifier_list();
138 cap_result->push_back(Typed_identifier("", int_type, loc));
139 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
141 cap_type->set_is_builtin();
142 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
144 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
145 print_type->set_is_varargs();
146 print_type->set_is_builtin();
147 this->globals_->add_function_declaration("print", NULL, print_type, loc);
149 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
150 print_type->set_is_varargs();
151 print_type->set_is_builtin();
152 this->globals_->add_function_declaration("println", NULL, print_type, loc);
154 Type *empty = Type::make_interface_type(NULL, loc);
155 Typed_identifier_list* panic_parms = new Typed_identifier_list();
156 panic_parms->push_back(Typed_identifier("e", empty, loc));
157 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
159 panic_type->set_is_builtin();
160 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
162 Typed_identifier_list* recover_result = new Typed_identifier_list();
163 recover_result->push_back(Typed_identifier("", empty, loc));
164 Function_type* recover_type = Type::make_function_type(NULL, NULL,
167 recover_type->set_is_builtin();
168 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
170 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
171 close_type->set_is_varargs();
172 close_type->set_is_builtin();
173 this->globals_->add_function_declaration("close", NULL, close_type, loc);
175 Typed_identifier_list* closed_result = new Typed_identifier_list();
176 closed_result->push_back(Typed_identifier("", Type::lookup_bool_type(),
178 Function_type* closed_type = Type::make_function_type(NULL, NULL,
180 closed_type->set_is_varargs();
181 closed_type->set_is_builtin();
182 this->globals_->add_function_declaration("closed", NULL, closed_type, loc);
184 Typed_identifier_list* copy_result = new Typed_identifier_list();
185 copy_result->push_back(Typed_identifier("", int_type, loc));
186 Function_type* copy_type = Type::make_function_type(NULL, NULL,
188 copy_type->set_is_varargs();
189 copy_type->set_is_builtin();
190 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
192 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
193 append_type->set_is_varargs();
194 append_type->set_is_builtin();
195 this->globals_->add_function_declaration("append", NULL, append_type, loc);
197 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
198 complex_type->set_is_varargs();
199 complex_type->set_is_builtin();
200 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
202 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
203 real_type->set_is_varargs();
204 real_type->set_is_builtin();
205 this->globals_->add_function_declaration("real", NULL, real_type, loc);
207 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
208 imag_type->set_is_varargs();
209 imag_type->set_is_builtin();
210 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
212 this->define_builtin_function_trees();
214 // Declare "init", to ensure that it is not defined with parameters
216 this->declare_function("init",
217 Type::make_function_type(NULL, NULL, NULL, loc),
221 // Munge name for use in an error message.
224 Gogo::message_name(const std::string& name)
226 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
229 // Get the package name.
232 Gogo::package_name() const
234 gcc_assert(this->package_ != NULL);
235 return this->package_->name();
238 // Set the package name.
241 Gogo::set_package_name(const std::string& package_name,
242 source_location location)
244 if (this->package_ != NULL && this->package_->name() != package_name)
246 error_at(location, "expected package %<%s%>",
247 Gogo::message_name(this->package_->name()).c_str());
251 // If the user did not specify a unique prefix, we always use "go".
252 // This in effect requires that the package name be unique.
253 if (this->unique_prefix_.empty())
254 this->unique_prefix_ = "go";
256 this->package_ = this->register_package(package_name, this->unique_prefix_,
259 // We used to permit people to qualify symbols with the current
260 // package name (e.g., P.x), but we no longer do.
261 // this->globals_->add_package(package_name, this->package_);
263 if (this->is_main_package())
265 // Declare "main" as a function which takes no parameters and
267 this->declare_function("main",
268 Type::make_function_type(NULL, NULL, NULL,
274 // Return whether this is the "main" package. This is not true if
275 // -fgo-prefix was used.
278 Gogo::is_main_package() const
280 return this->package_name() == "main" && !this->unique_prefix_specified_;
286 Gogo::import_package(const std::string& filename,
287 const std::string& local_name,
288 bool is_local_name_exported,
289 source_location location)
291 if (filename == "unsafe")
293 this->import_unsafe(local_name, is_local_name_exported, location);
297 Imports::const_iterator p = this->imports_.find(filename);
298 if (p != this->imports_.end())
300 Package* package = p->second;
301 package->set_location(location);
302 package->set_is_imported();
303 std::string ln = local_name;
304 bool is_ln_exported = is_local_name_exported;
307 ln = package->name();
308 is_ln_exported = Lex::is_exported_name(ln);
312 ln = this->pack_hidden_name(ln, is_ln_exported);
313 this->package_->bindings()->add_package(ln, package);
317 Bindings* bindings = package->bindings();
318 for (Bindings::const_declarations_iterator p =
319 bindings->begin_declarations();
320 p != bindings->end_declarations();
322 this->add_named_object(p->second);
327 Import::Stream* stream = Import::open_package(filename, location);
330 error_at(location, "import file %qs not found", filename.c_str());
334 Import imp(stream, location);
335 imp.register_builtin_types(this);
336 Package* package = imp.import(this, local_name, is_local_name_exported);
339 if (package->name() == this->package_name()
340 && package->unique_prefix() == this->unique_prefix())
342 ("imported package uses same package name and prefix "
343 "as package being compiled (see -fgo-prefix option)"));
345 this->imports_.insert(std::make_pair(filename, package));
346 package->set_is_imported();
352 // Add an import control function for an imported package to the list.
355 Gogo::add_import_init_fn(const std::string& package_name,
356 const std::string& init_name, int prio)
358 for (std::set<Import_init>::const_iterator p =
359 this->imported_init_fns_.begin();
360 p != this->imported_init_fns_.end();
363 if (p->init_name() == init_name
364 && (p->package_name() != package_name || p->priority() != prio))
366 error("duplicate package initialization name %qs",
367 Gogo::message_name(init_name).c_str());
368 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
369 Gogo::message_name(p->package_name()).c_str(),
371 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
372 Gogo::message_name(package_name).c_str(), prio);
377 this->imported_init_fns_.insert(Import_init(package_name, init_name,
381 // Return whether we are at the global binding level.
384 Gogo::in_global_scope() const
386 return this->functions_.empty();
389 // Return the current binding contour.
392 Gogo::current_bindings()
394 if (!this->functions_.empty())
395 return this->functions_.back().blocks.back()->bindings();
396 else if (this->package_ != NULL)
397 return this->package_->bindings();
399 return this->globals_;
403 Gogo::current_bindings() const
405 if (!this->functions_.empty())
406 return this->functions_.back().blocks.back()->bindings();
407 else if (this->package_ != NULL)
408 return this->package_->bindings();
410 return this->globals_;
413 // Return the current block.
416 Gogo::current_block()
418 if (this->functions_.empty())
421 return this->functions_.back().blocks.back();
424 // Look up a name in the current binding contour. If PFUNCTION is not
425 // NULL, set it to the function in which the name is defined, or NULL
426 // if the name is defined in global scope.
429 Gogo::lookup(const std::string& name, Named_object** pfunction) const
431 if (pfunction != NULL)
434 if (Gogo::is_sink_name(name))
435 return Named_object::make_sink();
437 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
438 p != this->functions_.rend();
441 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
444 if (pfunction != NULL)
445 *pfunction = p->function;
450 if (this->package_ != NULL)
452 Named_object* ret = this->package_->bindings()->lookup(name);
455 if (ret->package() != NULL)
456 ret->package()->set_used();
461 // We do not look in the global namespace. If we did, the global
462 // namespace would effectively hide names which were defined in
463 // package scope which we have not yet seen. Instead,
464 // define_global_names is called after parsing is over to connect
465 // undefined names at package scope with names defined at global
471 // Look up a name in the current block, without searching enclosing
475 Gogo::lookup_in_block(const std::string& name) const
477 gcc_assert(!this->functions_.empty());
478 gcc_assert(!this->functions_.back().blocks.empty());
479 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
482 // Look up a name in the global namespace.
485 Gogo::lookup_global(const char* name) const
487 return this->globals_->lookup(name);
490 // Add an imported package.
493 Gogo::add_imported_package(const std::string& real_name,
494 const std::string& alias_arg,
495 bool is_alias_exported,
496 const std::string& unique_prefix,
497 source_location location,
498 bool* padd_to_globals)
500 // FIXME: Now that we compile packages as a whole, should we permit
501 // importing the current package?
502 if (this->package_name() == real_name
503 && this->unique_prefix() == unique_prefix)
505 *padd_to_globals = false;
506 if (!alias_arg.empty() && alias_arg != ".")
508 std::string alias = this->pack_hidden_name(alias_arg,
510 this->package_->bindings()->add_package(alias, this->package_);
512 return this->package_;
514 else if (alias_arg == ".")
516 *padd_to_globals = true;
517 return this->register_package(real_name, unique_prefix, location);
519 else if (alias_arg == "_")
521 Package* ret = this->register_package(real_name, unique_prefix, location);
522 ret->set_uses_sink_alias();
527 *padd_to_globals = false;
528 std::string alias = alias_arg;
532 is_alias_exported = Lex::is_exported_name(alias);
534 alias = this->pack_hidden_name(alias, is_alias_exported);
535 Named_object* no = this->add_package(real_name, alias, unique_prefix,
537 if (!no->is_package())
539 return no->package_value();
546 Gogo::add_package(const std::string& real_name, const std::string& alias,
547 const std::string& unique_prefix, source_location location)
549 gcc_assert(this->in_global_scope());
551 // Register the package. Note that we might have already seen it in
552 // an earlier import.
553 Package* package = this->register_package(real_name, unique_prefix, location);
555 return this->package_->bindings()->add_package(alias, package);
558 // Register a package. This package may or may not be imported. This
559 // returns the Package structure for the package, creating if it
563 Gogo::register_package(const std::string& package_name,
564 const std::string& unique_prefix,
565 source_location location)
567 gcc_assert(!unique_prefix.empty() && !package_name.empty());
568 std::string name = unique_prefix + '.' + package_name;
569 Package* package = NULL;
570 std::pair<Packages::iterator, bool> ins =
571 this->packages_.insert(std::make_pair(name, package));
574 // We have seen this package name before.
575 package = ins.first->second;
576 gcc_assert(package != NULL);
577 gcc_assert(package->name() == package_name
578 && package->unique_prefix() == unique_prefix);
579 if (package->location() == UNKNOWN_LOCATION)
580 package->set_location(location);
584 // First time we have seen this package name.
585 package = new Package(package_name, unique_prefix, location);
586 gcc_assert(ins.first->second == NULL);
587 ins.first->second = package;
593 // Start compiling a function.
596 Gogo::start_function(const std::string& name, Function_type* type,
597 bool add_method_to_type, source_location location)
599 bool at_top_level = this->functions_.empty();
601 Block* block = new Block(NULL, location);
603 Function* enclosing = (at_top_level
605 : this->functions_.back().function->func_value());
607 Function* function = new Function(type, enclosing, block, location);
609 if (type->is_method())
611 const Typed_identifier* receiver = type->receiver();
612 Variable* this_param = new Variable(receiver->type(), NULL, false,
613 true, true, location);
614 std::string name = receiver->name();
617 // We need to give receivers a name since they wind up in
618 // DECL_ARGUMENTS. FIXME.
619 static unsigned int count;
621 snprintf(buf, sizeof buf, "r.%u", count);
625 block->bindings()->add_variable(name, NULL, this_param);
628 const Typed_identifier_list* parameters = type->parameters();
629 bool is_varargs = type->is_varargs();
630 if (parameters != NULL)
632 for (Typed_identifier_list::const_iterator p = parameters->begin();
633 p != parameters->end();
636 Variable* param = new Variable(p->type(), NULL, false, true, false,
638 if (is_varargs && p + 1 == parameters->end())
639 param->set_is_varargs_parameter();
641 std::string name = p->name();
642 if (name.empty() || Gogo::is_sink_name(name))
644 // We need to give parameters a name since they wind up
645 // in DECL_ARGUMENTS. FIXME.
646 static unsigned int count;
648 snprintf(buf, sizeof buf, "p.%u", count);
652 block->bindings()->add_variable(name, NULL, param);
656 function->create_named_result_variables(this);
658 const std::string* pname;
659 std::string nested_name;
664 // Invent a name for a nested function.
665 static int nested_count;
667 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
670 pname = &nested_name;
674 if (Gogo::is_sink_name(*pname))
676 static int sink_count;
678 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
680 ret = Named_object::make_function(buf, NULL, function);
682 else if (!type->is_method())
684 ret = this->package_->bindings()->add_function(*pname, NULL, function);
685 if (!ret->is_function() || ret->func_value() != function)
687 // Redefinition error. Invent a name to avoid knockon
689 static int redefinition_count;
691 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
692 ++redefinition_count;
693 ret = this->package_->bindings()->add_function(buf, NULL, function);
698 if (!add_method_to_type)
699 ret = Named_object::make_function(name, NULL, function);
702 gcc_assert(at_top_level);
703 Type* rtype = type->receiver()->type();
705 // We want to look through the pointer created by the
706 // parser, without getting an error if the type is not yet
708 if (rtype->classification() == Type::TYPE_POINTER)
709 rtype = rtype->points_to();
711 if (rtype->is_error_type())
712 ret = Named_object::make_function(name, NULL, function);
713 else if (rtype->named_type() != NULL)
715 ret = rtype->named_type()->add_method(name, function);
716 if (!ret->is_function())
718 // Redefinition error.
719 ret = Named_object::make_function(name, NULL, function);
722 else if (rtype->forward_declaration_type() != NULL)
724 Named_object* type_no =
725 rtype->forward_declaration_type()->named_object();
726 if (type_no->is_unknown())
728 // If we are seeing methods it really must be a
729 // type. Declare it as such. An alternative would
730 // be to support lists of methods for unknown
731 // expressions. Either way the error messages if
732 // this is not a type are going to get confusing.
733 Named_object* declared =
734 this->declare_package_type(type_no->name(),
735 type_no->location());
737 == type_no->unknown_value()->real_named_object());
739 ret = rtype->forward_declaration_type()->add_method(name,
745 this->package_->bindings()->add_method(ret);
748 this->functions_.resize(this->functions_.size() + 1);
749 Open_function& of(this->functions_.back());
751 of.blocks.push_back(block);
753 if (!type->is_method() && Gogo::unpack_hidden_name(name) == "init")
755 this->init_functions_.push_back(ret);
756 this->need_init_fn_ = true;
762 // Finish compiling a function.
765 Gogo::finish_function(source_location location)
767 this->finish_block(location);
768 gcc_assert(this->functions_.back().blocks.empty());
769 this->functions_.pop_back();
772 // Return the current function.
775 Gogo::current_function() const
777 gcc_assert(!this->functions_.empty());
778 return this->functions_.back().function;
781 // Start a new block.
784 Gogo::start_block(source_location location)
786 gcc_assert(!this->functions_.empty());
787 Block* block = new Block(this->current_block(), location);
788 this->functions_.back().blocks.push_back(block);
794 Gogo::finish_block(source_location location)
796 gcc_assert(!this->functions_.empty());
797 gcc_assert(!this->functions_.back().blocks.empty());
798 Block* block = this->functions_.back().blocks.back();
799 this->functions_.back().blocks.pop_back();
800 block->set_end_location(location);
804 // Add an unknown name.
807 Gogo::add_unknown_name(const std::string& name, source_location location)
809 return this->package_->bindings()->add_unknown_name(name, location);
812 // Declare a function.
815 Gogo::declare_function(const std::string& name, Function_type* type,
816 source_location location)
818 if (!type->is_method())
819 return this->current_bindings()->add_function_declaration(name, NULL, type,
823 // We don't bother to add this to the list of global
825 Type* rtype = type->receiver()->type();
827 // We want to look through the pointer created by the
828 // parser, without getting an error if the type is not yet
830 if (rtype->classification() == Type::TYPE_POINTER)
831 rtype = rtype->points_to();
833 if (rtype->is_error_type())
835 else if (rtype->named_type() != NULL)
836 return rtype->named_type()->add_method_declaration(name, NULL, type,
838 else if (rtype->forward_declaration_type() != NULL)
840 Forward_declaration_type* ftype = rtype->forward_declaration_type();
841 return ftype->add_method_declaration(name, type, location);
848 // Add a label definition.
851 Gogo::add_label_definition(const std::string& label_name,
852 source_location location)
854 gcc_assert(!this->functions_.empty());
855 Function* func = this->functions_.back().function->func_value();
856 Label* label = func->add_label_definition(label_name, location);
857 this->add_statement(Statement::make_label_statement(label, location));
861 // Add a label reference.
864 Gogo::add_label_reference(const std::string& label_name)
866 gcc_assert(!this->functions_.empty());
867 Function* func = this->functions_.back().function->func_value();
868 return func->add_label_reference(label_name);
874 Gogo::add_statement(Statement* statement)
876 gcc_assert(!this->functions_.empty()
877 && !this->functions_.back().blocks.empty());
878 this->functions_.back().blocks.back()->add_statement(statement);
884 Gogo::add_block(Block* block, source_location location)
886 gcc_assert(!this->functions_.empty()
887 && !this->functions_.back().blocks.empty());
888 Statement* statement = Statement::make_block_statement(block, location);
889 this->functions_.back().blocks.back()->add_statement(statement);
895 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
898 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
904 Gogo::add_type(const std::string& name, Type* type, source_location location)
906 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
908 if (!this->in_global_scope() && no->is_type())
909 no->type_value()->set_in_function(this->functions_.back().function);
915 Gogo::add_named_type(Named_type* type)
917 gcc_assert(this->in_global_scope());
918 this->current_bindings()->add_named_type(type);
924 Gogo::declare_type(const std::string& name, source_location location)
926 Bindings* bindings = this->current_bindings();
927 Named_object* no = bindings->add_type_declaration(name, NULL, location);
928 if (!this->in_global_scope() && no->is_type_declaration())
930 Named_object* f = this->functions_.back().function;
931 no->type_declaration_value()->set_in_function(f);
936 // Declare a type at the package level.
939 Gogo::declare_package_type(const std::string& name, source_location location)
941 return this->package_->bindings()->add_type_declaration(name, NULL, location);
944 // Define a type which was already declared.
947 Gogo::define_type(Named_object* no, Named_type* type)
949 this->current_bindings()->define_type(no, type);
955 Gogo::add_variable(const std::string& name, Variable* variable)
957 Named_object* no = this->current_bindings()->add_variable(name, NULL,
960 // In a function the middle-end wants to see a DECL_EXPR node.
963 && !no->var_value()->is_parameter()
964 && !this->functions_.empty())
965 this->add_statement(Statement::make_variable_declaration(no));
970 // Add a sink--a reference to the blank identifier _.
975 return Named_object::make_sink();
978 // Add a named object.
981 Gogo::add_named_object(Named_object* no)
983 this->current_bindings()->add_named_object(no);
986 // Record that we've seen an interface type.
989 Gogo::record_interface_type(Interface_type* itype)
991 this->interface_types_.push_back(itype);
994 // Return a name for a thunk object.
999 static int thunk_count;
1000 char thunk_name[50];
1001 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1006 // Return whether a function is a thunk.
1009 Gogo::is_thunk(const Named_object* no)
1011 return no->name().compare(0, 6, "$thunk") == 0;
1014 // Define the global names. We do this only after parsing all the
1015 // input files, because the program might define the global names
1019 Gogo::define_global_names()
1021 for (Bindings::const_declarations_iterator p =
1022 this->globals_->begin_declarations();
1023 p != this->globals_->end_declarations();
1026 Named_object* global_no = p->second;
1027 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1028 Named_object* no = this->package_->bindings()->lookup(name);
1032 if (no->is_type_declaration())
1034 if (global_no->is_type())
1036 if (no->type_declaration_value()->has_methods())
1037 error_at(no->location(),
1038 "may not define methods for global type");
1039 no->set_type_value(global_no->type_value());
1043 error_at(no->location(), "expected type");
1044 Type* errtype = Type::make_error_type();
1045 Named_object* err = Named_object::make_type("error", NULL,
1048 no->set_type_value(err->type_value());
1051 else if (no->is_unknown())
1052 no->unknown_value()->set_real_named_object(global_no);
1056 // Clear out names in file scope.
1059 Gogo::clear_file_scope()
1061 this->package_->bindings()->clear_file_scope();
1063 // Warn about packages which were imported but not used.
1064 for (Packages::iterator p = this->packages_.begin();
1065 p != this->packages_.end();
1068 Package* package = p->second;
1069 if (package != this->package_
1070 && package->is_imported()
1072 && !package->uses_sink_alias()
1074 error_at(package->location(), "imported and not used: %s",
1075 Gogo::message_name(package->name()).c_str());
1076 package->clear_is_imported();
1077 package->clear_uses_sink_alias();
1078 package->clear_used();
1082 // Traverse the tree.
1085 Gogo::traverse(Traverse* traverse)
1087 // Traverse the current package first for consistency. The other
1088 // packages will only contain imported types, constants, and
1090 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1092 for (Packages::const_iterator p = this->packages_.begin();
1093 p != this->packages_.end();
1096 if (p->second != this->package_)
1098 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1104 // Traversal class used to verify types.
1106 class Verify_types : public Traverse
1110 : Traverse(traverse_types)
1117 // Verify that a type is correct.
1120 Verify_types::type(Type* t)
1122 // Don't verify types defined in other packages.
1123 Named_type* nt = t->named_type();
1124 if (nt != NULL && nt->named_object()->package() != NULL)
1125 return TRAVERSE_SKIP_COMPONENTS;
1128 return TRAVERSE_SKIP_COMPONENTS;
1129 return TRAVERSE_CONTINUE;
1132 // Verify that all types are correct.
1135 Gogo::verify_types()
1137 Verify_types traverse;
1138 this->traverse(&traverse);
1141 // Traversal class used to lower parse tree.
1143 class Lower_parse_tree : public Traverse
1146 Lower_parse_tree(Gogo* gogo, Named_object* function)
1147 : Traverse(traverse_variables
1148 | traverse_constants
1149 | traverse_functions
1150 | traverse_statements
1151 | traverse_expressions),
1152 gogo_(gogo), function_(function), iota_value_(-1)
1156 variable(Named_object*);
1159 constant(Named_object*, bool);
1162 function(Named_object*);
1165 statement(Block*, size_t* pindex, Statement*);
1168 expression(Expression**);
1173 // The function we are traversing.
1174 Named_object* function_;
1175 // Value to use for the predeclared constant iota.
1179 // Lower variables. We handle variables specially to break loops in
1180 // which a variable initialization expression refers to itself. The
1181 // loop breaking is in lower_init_expression.
1184 Lower_parse_tree::variable(Named_object* no)
1186 if (no->is_variable())
1187 no->var_value()->lower_init_expression(this->gogo_, this->function_);
1188 return TRAVERSE_CONTINUE;
1191 // Lower constants. We handle constants specially so that we can set
1192 // the right value for the predeclared constant iota. This works in
1193 // conjunction with the way we lower Const_expression objects.
1196 Lower_parse_tree::constant(Named_object* no, bool)
1198 Named_constant* nc = no->const_value();
1200 // Don't get into trouble if the constant's initializer expression
1201 // refers to the constant itself.
1203 return TRAVERSE_CONTINUE;
1206 gcc_assert(this->iota_value_ == -1);
1207 this->iota_value_ = nc->iota_value();
1208 nc->traverse_expression(this);
1209 this->iota_value_ = -1;
1211 nc->clear_lowering();
1213 // We will traverse the expression a second time, but that will be
1216 return TRAVERSE_CONTINUE;
1219 // Lower function closure types. Record the function while lowering
1220 // it, so that we can pass it down when lowering an expression.
1223 Lower_parse_tree::function(Named_object* no)
1225 no->func_value()->set_closure_type();
1227 gcc_assert(this->function_ == NULL);
1228 this->function_ = no;
1229 int t = no->func_value()->traverse(this);
1230 this->function_ = NULL;
1232 if (t == TRAVERSE_EXIT)
1234 return TRAVERSE_SKIP_COMPONENTS;
1237 // Lower statement parse trees.
1240 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1242 // Lower the expressions first.
1243 int t = sorig->traverse_contents(this);
1244 if (t == TRAVERSE_EXIT)
1247 // Keep lowering until nothing changes.
1248 Statement* s = sorig;
1251 Statement* snew = s->lower(this->gogo_, block);
1255 t = s->traverse_contents(this);
1256 if (t == TRAVERSE_EXIT)
1261 block->replace_statement(*pindex, s);
1263 return TRAVERSE_SKIP_COMPONENTS;
1266 // Lower expression parse trees.
1269 Lower_parse_tree::expression(Expression** pexpr)
1271 // We have to lower all subexpressions first, so that we can get
1272 // their type if necessary. This is awkward, because we don't have
1273 // a postorder traversal pass.
1274 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1275 return TRAVERSE_EXIT;
1276 // Keep lowering until nothing changes.
1279 Expression* e = *pexpr;
1280 Expression* enew = e->lower(this->gogo_, this->function_,
1286 return TRAVERSE_SKIP_COMPONENTS;
1289 // Lower the parse tree. This is called after the parse is complete,
1290 // when all names should be resolved.
1293 Gogo::lower_parse_tree()
1295 Lower_parse_tree lower_parse_tree(this, NULL);
1296 this->traverse(&lower_parse_tree);
1299 // Lower an expression.
1302 Gogo::lower_expression(Named_object* function, Expression** pexpr)
1304 Lower_parse_tree lower_parse_tree(this, function);
1305 lower_parse_tree.expression(pexpr);
1308 // Lower a constant. This is called when lowering a reference to a
1309 // constant. We have to make sure that the constant has already been
1313 Gogo::lower_constant(Named_object* no)
1315 gcc_assert(no->is_const());
1316 Lower_parse_tree lower(this, NULL);
1317 lower.constant(no, false);
1320 // Look for interface types to finalize methods of inherited
1323 class Finalize_methods : public Traverse
1326 Finalize_methods(Gogo* gogo)
1327 : Traverse(traverse_types),
1338 // Finalize the methods of an interface type.
1341 Finalize_methods::type(Type* t)
1343 // Check the classification so that we don't finalize the methods
1344 // twice for a named interface type.
1345 switch (t->classification())
1347 case Type::TYPE_INTERFACE:
1348 t->interface_type()->finalize_methods();
1351 case Type::TYPE_NAMED:
1353 // We have to finalize the methods of the real type first.
1354 // But if the real type is a struct type, then we only want to
1355 // finalize the methods of the field types, not of the struct
1356 // type itself. We don't want to add methods to the struct,
1357 // since it has a name.
1358 Type* rt = t->named_type()->real_type();
1359 if (rt->classification() != Type::TYPE_STRUCT)
1361 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1362 return TRAVERSE_EXIT;
1366 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1367 return TRAVERSE_EXIT;
1370 t->named_type()->finalize_methods(this->gogo_);
1372 return TRAVERSE_SKIP_COMPONENTS;
1375 case Type::TYPE_STRUCT:
1376 t->struct_type()->finalize_methods(this->gogo_);
1383 return TRAVERSE_CONTINUE;
1386 // Finalize method lists and build stub methods for types.
1389 Gogo::finalize_methods()
1391 Finalize_methods finalize(this);
1392 this->traverse(&finalize);
1395 // Set types for unspecified variables and constants.
1398 Gogo::determine_types()
1400 Bindings* bindings = this->current_bindings();
1401 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1402 p != bindings->end_definitions();
1405 if ((*p)->is_function())
1406 (*p)->func_value()->determine_types();
1407 else if ((*p)->is_variable())
1408 (*p)->var_value()->determine_type();
1409 else if ((*p)->is_const())
1410 (*p)->const_value()->determine_type();
1412 // See if a variable requires us to build an initialization
1413 // function. We know that we will see all global variables
1415 if (!this->need_init_fn_ && (*p)->is_variable())
1417 Variable* variable = (*p)->var_value();
1419 // If this is a global variable which requires runtime
1420 // initialization, we need an initialization function.
1421 if (!variable->is_global())
1423 else if (variable->init() == NULL)
1425 else if (variable->type()->interface_type() != NULL)
1426 this->need_init_fn_ = true;
1427 else if (variable->init()->is_constant())
1429 else if (!variable->init()->is_composite_literal())
1430 this->need_init_fn_ = true;
1431 else if (variable->init()->is_nonconstant_composite_literal())
1432 this->need_init_fn_ = true;
1434 // If this is a global variable which holds a pointer value,
1435 // then we need an initialization function to register it as a
1437 if (variable->is_global() && variable->type()->has_pointer())
1438 this->need_init_fn_ = true;
1442 // Determine the types of constants in packages.
1443 for (Packages::const_iterator p = this->packages_.begin();
1444 p != this->packages_.end();
1446 p->second->determine_types();
1449 // Traversal class used for type checking.
1451 class Check_types_traverse : public Traverse
1454 Check_types_traverse(Gogo* gogo)
1455 : Traverse(traverse_variables
1456 | traverse_constants
1457 | traverse_statements
1458 | traverse_expressions),
1463 variable(Named_object*);
1466 constant(Named_object*, bool);
1469 statement(Block*, size_t* pindex, Statement*);
1472 expression(Expression**);
1479 // Check that a variable initializer has the right type.
1482 Check_types_traverse::variable(Named_object* named_object)
1484 if (named_object->is_variable())
1486 Variable* var = named_object->var_value();
1487 Expression* init = var->init();
1490 && !Type::are_assignable(var->type(), init->type(), &reason))
1493 error_at(var->location(), "incompatible type in initialization");
1495 error_at(var->location(),
1496 "incompatible type in initialization (%s)",
1501 return TRAVERSE_CONTINUE;
1504 // Check that a constant initializer has the right type.
1507 Check_types_traverse::constant(Named_object* named_object, bool)
1509 Named_constant* constant = named_object->const_value();
1510 Type* ctype = constant->type();
1511 if (ctype->integer_type() == NULL
1512 && ctype->float_type() == NULL
1513 && ctype->complex_type() == NULL
1514 && !ctype->is_boolean_type()
1515 && !ctype->is_string_type())
1517 if (!ctype->is_error_type())
1518 error_at(constant->location(), "invalid constant type");
1519 constant->set_error();
1521 else if (!constant->expr()->is_constant())
1523 error_at(constant->expr()->location(), "expression is not constant");
1524 constant->set_error();
1526 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1529 error_at(constant->location(),
1530 "initialization expression has wrong type");
1531 constant->set_error();
1533 return TRAVERSE_CONTINUE;
1536 // Check that types are valid in a statement.
1539 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1541 s->check_types(this->gogo_);
1542 return TRAVERSE_CONTINUE;
1545 // Check that types are valid in an expression.
1548 Check_types_traverse::expression(Expression** expr)
1550 (*expr)->check_types(this->gogo_);
1551 return TRAVERSE_CONTINUE;
1554 // Check that types are valid.
1559 Check_types_traverse traverse(this);
1560 this->traverse(&traverse);
1563 // Check the types in a single block.
1566 Gogo::check_types_in_block(Block* block)
1568 Check_types_traverse traverse(this);
1569 block->traverse(&traverse);
1572 // A traversal class used to find a single shortcut operator within an
1575 class Find_shortcut : public Traverse
1579 : Traverse(traverse_blocks
1580 | traverse_statements
1581 | traverse_expressions),
1585 // A pointer to the expression which was found, or NULL if none was
1589 { return this->found_; }
1594 { return TRAVERSE_SKIP_COMPONENTS; }
1597 statement(Block*, size_t*, Statement*)
1598 { return TRAVERSE_SKIP_COMPONENTS; }
1601 expression(Expression**);
1604 Expression** found_;
1607 // Find a shortcut expression.
1610 Find_shortcut::expression(Expression** pexpr)
1612 Expression* expr = *pexpr;
1613 Binary_expression* be = expr->binary_expression();
1615 return TRAVERSE_CONTINUE;
1616 Operator op = be->op();
1617 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1618 return TRAVERSE_CONTINUE;
1619 gcc_assert(this->found_ == NULL);
1620 this->found_ = pexpr;
1621 return TRAVERSE_EXIT;
1624 // A traversal class used to turn shortcut operators into explicit if
1627 class Shortcuts : public Traverse
1630 Shortcuts(Gogo* gogo)
1631 : Traverse(traverse_variables
1632 | traverse_statements),
1638 variable(Named_object*);
1641 statement(Block*, size_t*, Statement*);
1644 // Convert a shortcut operator.
1646 convert_shortcut(Block* enclosing, Expression** pshortcut);
1652 // Remove shortcut operators in a single statement.
1655 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1657 // FIXME: This approach doesn't work for switch statements, because
1658 // we add the new statements before the whole switch when we need to
1659 // instead add them just before the switch expression. The right
1660 // fix is probably to lower switch statements with nonconstant cases
1661 // to a series of conditionals.
1662 if (s->switch_statement() != NULL)
1663 return TRAVERSE_CONTINUE;
1667 Find_shortcut find_shortcut;
1669 // If S is a variable declaration, then ordinary traversal won't
1670 // do anything. We want to explicitly traverse the
1671 // initialization expression if there is one.
1672 Variable_declaration_statement* vds = s->variable_declaration_statement();
1673 Expression* init = NULL;
1675 s->traverse_contents(&find_shortcut);
1678 init = vds->var()->var_value()->init();
1680 return TRAVERSE_CONTINUE;
1681 init->traverse(&init, &find_shortcut);
1683 Expression** pshortcut = find_shortcut.found();
1684 if (pshortcut == NULL)
1685 return TRAVERSE_CONTINUE;
1687 Statement* snew = this->convert_shortcut(block, pshortcut);
1688 block->insert_statement_before(*pindex, snew);
1691 if (pshortcut == &init)
1692 vds->var()->var_value()->set_init(init);
1696 // Remove shortcut operators in the initializer of a global variable.
1699 Shortcuts::variable(Named_object* no)
1701 if (no->is_result_variable())
1702 return TRAVERSE_CONTINUE;
1703 Variable* var = no->var_value();
1704 Expression* init = var->init();
1705 if (!var->is_global() || init == NULL)
1706 return TRAVERSE_CONTINUE;
1710 Find_shortcut find_shortcut;
1711 init->traverse(&init, &find_shortcut);
1712 Expression** pshortcut = find_shortcut.found();
1713 if (pshortcut == NULL)
1714 return TRAVERSE_CONTINUE;
1716 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1717 var->add_preinit_statement(this->gogo_, snew);
1718 if (pshortcut == &init)
1719 var->set_init(init);
1723 // Given an expression which uses a shortcut operator, return a
1724 // statement which implements it, and update *PSHORTCUT accordingly.
1727 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1729 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1730 Expression* left = shortcut->left();
1731 Expression* right = shortcut->right();
1732 source_location loc = shortcut->location();
1734 Block* retblock = new Block(enclosing, loc);
1735 retblock->set_end_location(loc);
1737 Temporary_statement* ts = Statement::make_temporary(Type::make_boolean_type(),
1739 retblock->add_statement(ts);
1741 Block* block = new Block(retblock, loc);
1742 block->set_end_location(loc);
1743 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1744 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1745 block->add_statement(assign);
1747 Expression* cond = Expression::make_temporary_reference(ts, loc);
1748 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1749 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1751 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1753 retblock->add_statement(if_statement);
1755 *pshortcut = Expression::make_temporary_reference(ts, loc);
1759 // Now convert any shortcut operators in LEFT and RIGHT.
1760 Shortcuts shortcuts(this->gogo_);
1761 retblock->traverse(&shortcuts);
1763 return Statement::make_block_statement(retblock, loc);
1766 // Turn shortcut operators into explicit if statements. Doing this
1767 // considerably simplifies the order of evaluation rules.
1770 Gogo::remove_shortcuts()
1772 Shortcuts shortcuts(this);
1773 this->traverse(&shortcuts);
1776 // A traversal class which finds all the expressions which must be
1777 // evaluated in order within a statement or larger expression. This
1778 // is used to implement the rules about order of evaluation.
1780 class Find_eval_ordering : public Traverse
1783 typedef std::vector<Expression**> Expression_pointers;
1786 Find_eval_ordering()
1787 : Traverse(traverse_blocks
1788 | traverse_statements
1789 | traverse_expressions),
1795 { return this->exprs_.size(); }
1797 typedef Expression_pointers::const_iterator const_iterator;
1801 { return this->exprs_.begin(); }
1805 { return this->exprs_.end(); }
1810 { return TRAVERSE_SKIP_COMPONENTS; }
1813 statement(Block*, size_t*, Statement*)
1814 { return TRAVERSE_SKIP_COMPONENTS; }
1817 expression(Expression**);
1820 // A list of pointers to expressions with side-effects.
1821 Expression_pointers exprs_;
1824 // If an expression must be evaluated in order, put it on the list.
1827 Find_eval_ordering::expression(Expression** expression_pointer)
1829 // We have to look at subexpressions before this one.
1830 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1831 return TRAVERSE_EXIT;
1832 if ((*expression_pointer)->must_eval_in_order())
1833 this->exprs_.push_back(expression_pointer);
1834 return TRAVERSE_SKIP_COMPONENTS;
1837 // A traversal class for ordering evaluations.
1839 class Order_eval : public Traverse
1842 Order_eval(Gogo* gogo)
1843 : Traverse(traverse_variables
1844 | traverse_statements),
1849 variable(Named_object*);
1852 statement(Block*, size_t*, Statement*);
1859 // Implement the order of evaluation rules for a statement.
1862 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1864 // FIXME: This approach doesn't work for switch statements, because
1865 // we add the new statements before the whole switch when we need to
1866 // instead add them just before the switch expression. The right
1867 // fix is probably to lower switch statements with nonconstant cases
1868 // to a series of conditionals.
1869 if (s->switch_statement() != NULL)
1870 return TRAVERSE_CONTINUE;
1872 Find_eval_ordering find_eval_ordering;
1874 // If S is a variable declaration, then ordinary traversal won't do
1875 // anything. We want to explicitly traverse the initialization
1876 // expression if there is one.
1877 Variable_declaration_statement* vds = s->variable_declaration_statement();
1878 Expression* init = NULL;
1879 Expression* orig_init = NULL;
1881 s->traverse_contents(&find_eval_ordering);
1884 init = vds->var()->var_value()->init();
1886 return TRAVERSE_CONTINUE;
1889 // It might seem that this could be
1890 // init->traverse_subexpressions. Unfortunately that can fail
1893 // newvar, err := call(arg())
1894 // Here newvar will have an init of call result 0 of
1895 // call(arg()). If we only traverse subexpressions, we will
1896 // only find arg(), and we won't bother to move anything out.
1897 // Then we get to the assignment to err, we will traverse the
1898 // whole statement, and this time we will find both call() and
1899 // arg(), and so we will move them out. This will cause them to
1900 // be put into temporary variables before the assignment to err
1901 // but after the declaration of newvar. To avoid that problem,
1902 // we traverse the entire expression here.
1903 Expression::traverse(&init, &find_eval_ordering);
1906 if (find_eval_ordering.size() <= 1)
1908 // If there is only one expression with a side-effect, we can
1909 // leave it in place.
1910 return TRAVERSE_CONTINUE;
1913 bool is_thunk = s->thunk_statement() != NULL;
1914 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1915 p != find_eval_ordering.end();
1918 Expression** pexpr = *p;
1920 // If the last expression is a send or receive expression, we
1921 // may be ignoring the value; we don't want to evaluate it
1923 if (p + 1 == find_eval_ordering.end()
1924 && ((*pexpr)->classification() == Expression::EXPRESSION_SEND
1925 || (*pexpr)->classification() == Expression::EXPRESSION_RECEIVE))
1928 // The last expression in a thunk will be the call passed to go
1929 // or defer, which we must not evaluate early.
1930 if (is_thunk && p + 1 == find_eval_ordering.end())
1933 source_location loc = (*pexpr)->location();
1934 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1935 block->insert_statement_before(*pindex, ts);
1938 *pexpr = Expression::make_temporary_reference(ts, loc);
1941 if (init != orig_init)
1942 vds->var()->var_value()->set_init(init);
1944 return TRAVERSE_CONTINUE;
1947 // Implement the order of evaluation rules for the initializer of a
1951 Order_eval::variable(Named_object* no)
1953 if (no->is_result_variable())
1954 return TRAVERSE_CONTINUE;
1955 Variable* var = no->var_value();
1956 Expression* init = var->init();
1957 if (!var->is_global() || init == NULL)
1958 return TRAVERSE_CONTINUE;
1960 Find_eval_ordering find_eval_ordering;
1961 init->traverse_subexpressions(&find_eval_ordering);
1963 if (find_eval_ordering.size() <= 1)
1965 // If there is only one expression with a side-effect, we can
1966 // leave it in place.
1967 return TRAVERSE_SKIP_COMPONENTS;
1970 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1971 p != find_eval_ordering.end();
1974 Expression** pexpr = *p;
1975 source_location loc = (*pexpr)->location();
1976 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1977 var->add_preinit_statement(this->gogo_, ts);
1978 *pexpr = Expression::make_temporary_reference(ts, loc);
1981 return TRAVERSE_SKIP_COMPONENTS;
1984 // Use temporary variables to implement the order of evaluation rules.
1987 Gogo::order_evaluations()
1989 Order_eval order_eval(this);
1990 this->traverse(&order_eval);
1993 // Traversal to convert calls to the predeclared recover function to
1994 // pass in an argument indicating whether it can recover from a panic
1997 class Convert_recover : public Traverse
2000 Convert_recover(Named_object* arg)
2001 : Traverse(traverse_expressions),
2007 expression(Expression**);
2010 // The argument to pass to the function.
2014 // Convert calls to recover.
2017 Convert_recover::expression(Expression** pp)
2019 Call_expression* ce = (*pp)->call_expression();
2020 if (ce != NULL && ce->is_recover_call())
2021 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2023 return TRAVERSE_CONTINUE;
2026 // Traversal for build_recover_thunks.
2028 class Build_recover_thunks : public Traverse
2031 Build_recover_thunks(Gogo* gogo)
2032 : Traverse(traverse_functions),
2037 function(Named_object*);
2041 can_recover_arg(source_location);
2047 // If this function calls recover, turn it into a thunk.
2050 Build_recover_thunks::function(Named_object* orig_no)
2052 Function* orig_func = orig_no->func_value();
2053 if (!orig_func->calls_recover()
2054 || orig_func->is_recover_thunk()
2055 || orig_func->has_recover_thunk())
2056 return TRAVERSE_CONTINUE;
2058 Gogo* gogo = this->gogo_;
2059 source_location location = orig_func->location();
2064 Function_type* orig_fntype = orig_func->type();
2065 Typed_identifier_list* new_params = new Typed_identifier_list();
2066 std::string receiver_name;
2067 if (orig_fntype->is_method())
2069 const Typed_identifier* receiver = orig_fntype->receiver();
2070 snprintf(buf, sizeof buf, "rt.%u", count);
2072 receiver_name = buf;
2073 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2074 receiver->location()));
2076 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2077 if (orig_params != NULL && !orig_params->empty())
2079 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2080 p != orig_params->end();
2083 snprintf(buf, sizeof buf, "pt.%u", count);
2085 new_params->push_back(Typed_identifier(buf, p->type(),
2089 snprintf(buf, sizeof buf, "pr.%u", count);
2091 std::string can_recover_name = buf;
2092 new_params->push_back(Typed_identifier(can_recover_name,
2093 Type::make_boolean_type(),
2094 orig_fntype->location()));
2096 const Typed_identifier_list* orig_results = orig_fntype->results();
2097 Typed_identifier_list* new_results;
2098 if (orig_results == NULL || orig_results->empty())
2102 new_results = new Typed_identifier_list();
2103 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2104 p != orig_results->end();
2106 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2109 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2111 orig_fntype->location());
2112 if (orig_fntype->is_varargs())
2113 new_fntype->set_is_varargs();
2115 std::string name = orig_no->name() + "$recover";
2116 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2118 Function *new_func = new_no->func_value();
2119 if (orig_func->enclosing() != NULL)
2120 new_func->set_enclosing(orig_func->enclosing());
2122 // We build the code for the original function attached to the new
2123 // function, and then swap the original and new function bodies.
2124 // This means that existing references to the original function will
2125 // then refer to the new function. That makes this code a little
2126 // confusing, in that the reference to NEW_NO really refers to the
2127 // other function, not the one we are building.
2129 Expression* closure = NULL;
2130 if (orig_func->needs_closure())
2132 Named_object* orig_closure_no = orig_func->closure_var();
2133 Variable* orig_closure_var = orig_closure_no->var_value();
2134 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2135 true, false, location);
2136 snprintf(buf, sizeof buf, "closure.%u", count);
2138 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2140 new_func->set_closure_var(new_closure_no);
2141 closure = Expression::make_var_reference(new_closure_no, location);
2144 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2146 Expression_list* args = new Expression_list();
2147 if (new_params != NULL)
2149 // Note that we skip the last parameter, which is the boolean
2150 // indicating whether recover can succed.
2151 for (Typed_identifier_list::const_iterator p = new_params->begin();
2152 p + 1 != new_params->end();
2155 Named_object* p_no = gogo->lookup(p->name(), NULL);
2156 gcc_assert(p_no != NULL
2157 && p_no->is_variable()
2158 && p_no->var_value()->is_parameter());
2159 args->push_back(Expression::make_var_reference(p_no, location));
2162 args->push_back(this->can_recover_arg(location));
2164 Call_expression* call = Expression::make_call(fn, args, false, location);
2167 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2168 s = Statement::make_statement(call);
2171 Expression_list* vals = new Expression_list();
2172 size_t rc = orig_fntype->results()->size();
2174 vals->push_back(call);
2177 for (size_t i = 0; i < rc; ++i)
2178 vals->push_back(Expression::make_call_result(call, i));
2180 s = Statement::make_return_statement(new_func->type()->results(),
2183 s->determine_types();
2184 gogo->add_statement(s);
2186 gogo->finish_function(location);
2188 // Swap the function bodies and types.
2189 new_func->swap_for_recover(orig_func);
2190 orig_func->set_is_recover_thunk();
2191 new_func->set_calls_recover();
2192 new_func->set_has_recover_thunk();
2194 Bindings* orig_bindings = orig_func->block()->bindings();
2195 Bindings* new_bindings = new_func->block()->bindings();
2196 if (orig_fntype->is_method())
2198 // We changed the receiver to be a regular parameter. We have
2199 // to update the binding accordingly in both functions.
2200 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2201 gcc_assert(orig_rec_no != NULL
2202 && orig_rec_no->is_variable()
2203 && !orig_rec_no->var_value()->is_receiver());
2204 orig_rec_no->var_value()->set_is_receiver();
2206 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2207 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2208 gcc_assert(new_rec_no != NULL
2209 && new_rec_no->is_variable()
2210 && new_rec_no->var_value()->is_receiver());
2211 new_rec_no->var_value()->set_is_not_receiver();
2214 // Because we flipped blocks but not types, the can_recover
2215 // parameter appears in the (now) old bindings as a parameter.
2216 // Change it to a local variable, whereupon it will be discarded.
2217 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2218 gcc_assert(can_recover_no != NULL
2219 && can_recover_no->is_variable()
2220 && can_recover_no->var_value()->is_parameter());
2221 orig_bindings->remove_binding(can_recover_no);
2223 // Add the can_recover argument to the (now) new bindings, and
2224 // attach it to any recover statements.
2225 Variable* can_recover_var = new Variable(Type::make_boolean_type(), NULL,
2226 false, true, false, location);
2227 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2229 Convert_recover convert_recover(can_recover_no);
2230 new_func->traverse(&convert_recover);
2232 // Update the function pointers in any named results.
2233 new_func->update_named_result_variables();
2234 orig_func->update_named_result_variables();
2236 return TRAVERSE_CONTINUE;
2239 // Return the expression to pass for the .can_recover parameter to the
2240 // new function. This indicates whether a call to recover may return
2241 // non-nil. The expression is
2242 // __go_can_recover(__builtin_return_address()).
2245 Build_recover_thunks::can_recover_arg(source_location location)
2247 static Named_object* builtin_return_address;
2248 if (builtin_return_address == NULL)
2250 const source_location bloc = BUILTINS_LOCATION;
2252 Typed_identifier_list* param_types = new Typed_identifier_list();
2253 Type* uint_type = Type::lookup_integer_type("uint");
2254 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2256 Typed_identifier_list* return_types = new Typed_identifier_list();
2257 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2258 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2260 Function_type* fntype = Type::make_function_type(NULL, param_types,
2261 return_types, bloc);
2262 builtin_return_address =
2263 Named_object::make_function_declaration("__builtin_return_address",
2264 NULL, fntype, bloc);
2265 const char* n = "__builtin_return_address";
2266 builtin_return_address->func_declaration_value()->set_asm_name(n);
2269 static Named_object* can_recover;
2270 if (can_recover == NULL)
2272 const source_location bloc = BUILTINS_LOCATION;
2273 Typed_identifier_list* param_types = new Typed_identifier_list();
2274 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2275 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2276 Type* boolean_type = Type::make_boolean_type();
2277 Typed_identifier_list* results = new Typed_identifier_list();
2278 results->push_back(Typed_identifier("", boolean_type, bloc));
2279 Function_type* fntype = Type::make_function_type(NULL, param_types,
2281 can_recover = Named_object::make_function_declaration("__go_can_recover",
2284 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2287 Expression* fn = Expression::make_func_reference(builtin_return_address,
2291 mpz_init_set_ui(zval, 0UL);
2292 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2294 Expression_list *args = new Expression_list();
2295 args->push_back(zexpr);
2297 Expression* call = Expression::make_call(fn, args, false, location);
2299 args = new Expression_list();
2300 args->push_back(call);
2302 fn = Expression::make_func_reference(can_recover, NULL, location);
2303 return Expression::make_call(fn, args, false, location);
2306 // Build thunks for functions which call recover. We build a new
2307 // function with an extra parameter, which is whether a call to
2308 // recover can succeed. We then move the body of this function to
2309 // that one. We then turn this function into a thunk which calls the
2310 // new one, passing the value of
2311 // __go_can_recover(__builtin_return_address()). The function will be
2312 // marked as not splitting the stack. This will cooperate with the
2313 // implementation of defer to make recover do the right thing.
2316 Gogo::build_recover_thunks()
2318 Build_recover_thunks build_recover_thunks(this);
2319 this->traverse(&build_recover_thunks);
2322 // Look for named types to see whether we need to create an interface
2325 class Build_method_tables : public Traverse
2328 Build_method_tables(Gogo* gogo,
2329 const std::vector<Interface_type*>& interfaces)
2330 : Traverse(traverse_types),
2331 gogo_(gogo), interfaces_(interfaces)
2340 // A list of locally defined interfaces which have hidden methods.
2341 const std::vector<Interface_type*>& interfaces_;
2344 // Build all required interface method tables for types. We need to
2345 // ensure that we have an interface method table for every interface
2346 // which has a hidden method, for every named type which implements
2347 // that interface. Normally we can just build interface method tables
2348 // as we need them. However, in some cases we can require an
2349 // interface method table for an interface defined in a different
2350 // package for a type defined in that package. If that interface and
2351 // type both use a hidden method, that is OK. However, we will not be
2352 // able to build that interface method table when we need it, because
2353 // the type's hidden method will be static. So we have to build it
2354 // here, and just refer it from other packages as needed.
2357 Gogo::build_interface_method_tables()
2359 std::vector<Interface_type*> hidden_interfaces;
2360 hidden_interfaces.reserve(this->interface_types_.size());
2361 for (std::vector<Interface_type*>::const_iterator pi =
2362 this->interface_types_.begin();
2363 pi != this->interface_types_.end();
2366 const Typed_identifier_list* methods = (*pi)->methods();
2367 if (methods == NULL)
2369 for (Typed_identifier_list::const_iterator pm = methods->begin();
2370 pm != methods->end();
2373 if (Gogo::is_hidden_name(pm->name()))
2375 hidden_interfaces.push_back(*pi);
2381 if (!hidden_interfaces.empty())
2383 // Now traverse the tree looking for all named types.
2384 Build_method_tables bmt(this, hidden_interfaces);
2385 this->traverse(&bmt);
2388 // We no longer need the list of interfaces.
2390 this->interface_types_.clear();
2393 // This is called for each type. For a named type, for each of the
2394 // interfaces with hidden methods that it implements, create the
2398 Build_method_tables::type(Type* type)
2400 Named_type* nt = type->named_type();
2403 for (std::vector<Interface_type*>::const_iterator p =
2404 this->interfaces_.begin();
2405 p != this->interfaces_.end();
2408 // We ask whether a pointer to the named type implements the
2409 // interface, because a pointer can implement more methods
2411 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2413 nt->interface_method_table(this->gogo_, *p, false);
2414 nt->interface_method_table(this->gogo_, *p, true);
2418 return TRAVERSE_CONTINUE;
2421 // Traversal class used to check for return statements.
2423 class Check_return_statements_traverse : public Traverse
2426 Check_return_statements_traverse()
2427 : Traverse(traverse_functions)
2431 function(Named_object*);
2434 // Check that a function has a return statement if it needs one.
2437 Check_return_statements_traverse::function(Named_object* no)
2439 Function* func = no->func_value();
2440 const Function_type* fntype = func->type();
2441 const Typed_identifier_list* results = fntype->results();
2443 // We only need a return statement if there is a return value.
2444 if (results == NULL || results->empty())
2445 return TRAVERSE_CONTINUE;
2447 if (func->block()->may_fall_through())
2448 error_at(func->location(), "control reaches end of non-void function");
2450 return TRAVERSE_CONTINUE;
2453 // Check return statements.
2456 Gogo::check_return_statements()
2458 Check_return_statements_traverse traverse;
2459 this->traverse(&traverse);
2462 // Get the unique prefix to use before all exported symbols. This
2463 // must be unique across the entire link.
2466 Gogo::unique_prefix() const
2468 gcc_assert(!this->unique_prefix_.empty());
2469 return this->unique_prefix_;
2472 // Set the unique prefix to use before all exported symbols. This
2473 // comes from the command line option -fgo-prefix=XXX.
2476 Gogo::set_unique_prefix(const std::string& arg)
2478 gcc_assert(this->unique_prefix_.empty());
2479 this->unique_prefix_ = arg;
2480 this->unique_prefix_specified_ = true;
2483 // Work out the package priority. It is one more than the maximum
2484 // priority of an imported package.
2487 Gogo::package_priority() const
2490 for (Packages::const_iterator p = this->packages_.begin();
2491 p != this->packages_.end();
2493 if (p->second->priority() > priority)
2494 priority = p->second->priority();
2495 return priority + 1;
2498 // Export identifiers as requested.
2503 // For now we always stream to a section. Later we may want to
2504 // support streaming to a separate file.
2505 Stream_to_section stream;
2507 Export exp(&stream);
2508 exp.register_builtin_types(this);
2509 exp.export_globals(this->package_name(),
2510 this->unique_prefix(),
2511 this->package_priority(),
2512 (this->need_init_fn_ && !this->is_main_package()
2513 ? this->get_init_fn_name()
2515 this->imported_init_fns_,
2516 this->package_->bindings());
2521 Function::Function(Function_type* type, Function* enclosing, Block* block,
2522 source_location location)
2523 : type_(type), enclosing_(enclosing), named_results_(NULL),
2524 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2525 defer_stack_(NULL), calls_recover_(false), is_recover_thunk_(false),
2526 has_recover_thunk_(false)
2530 // Create the named result variables.
2533 Function::create_named_result_variables(Gogo* gogo)
2535 const Typed_identifier_list* results = this->type_->results();
2538 || results->front().name().empty())
2541 this->named_results_ = new Named_results();
2542 this->named_results_->reserve(results->size());
2544 Block* block = this->block_;
2546 for (Typed_identifier_list::const_iterator p = results->begin();
2547 p != results->end();
2550 std::string name = p->name();
2551 if (Gogo::is_sink_name(name))
2553 static int unnamed_result_counter;
2555 snprintf(buf, sizeof buf, "_$%d", unnamed_result_counter);
2556 ++unnamed_result_counter;
2557 name = gogo->pack_hidden_name(buf, false);
2559 Result_variable* result = new Result_variable(p->type(), this, index);
2560 Named_object* no = block->bindings()->add_result_variable(name, result);
2561 this->named_results_->push_back(no);
2565 // Update the named result variables when cloning a function which
2569 Function::update_named_result_variables()
2571 if (this->named_results_ == NULL)
2574 for (Named_results::iterator p = this->named_results_->begin();
2575 p != this->named_results_->end();
2577 (*p)->result_var_value()->set_function(this);
2580 // Return the closure variable, creating it if necessary.
2583 Function::closure_var()
2585 if (this->closure_var_ == NULL)
2587 // We don't know the type of the variable yet. We add fields as
2589 source_location loc = this->type_->location();
2590 Struct_field_list* sfl = new Struct_field_list;
2591 Type* struct_type = Type::make_struct_type(sfl, loc);
2592 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2593 NULL, false, true, false, loc);
2594 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2595 // Note that the new variable is not in any binding contour.
2597 return this->closure_var_;
2600 // Set the type of the closure variable.
2603 Function::set_closure_type()
2605 if (this->closure_var_ == NULL)
2607 Named_object* closure = this->closure_var_;
2608 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2609 unsigned int index = 0;
2610 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2611 p != this->closure_fields_.end();
2614 Named_object* no = p->first;
2616 snprintf(buf, sizeof buf, "%u", index);
2617 std::string n = no->name() + buf;
2619 if (no->is_variable())
2620 var_type = no->var_value()->type();
2622 var_type = no->result_var_value()->type();
2623 Type* field_type = Type::make_pointer_type(var_type);
2624 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2628 // Return whether this function is a method.
2631 Function::is_method() const
2633 return this->type_->is_method();
2636 // Add a label definition.
2639 Function::add_label_definition(const std::string& label_name,
2640 source_location location)
2642 Label* lnull = NULL;
2643 std::pair<Labels::iterator, bool> ins =
2644 this->labels_.insert(std::make_pair(label_name, lnull));
2647 // This is a new label.
2648 Label* label = new Label(label_name);
2649 label->define(location);
2650 ins.first->second = label;
2655 // The label was already in the hash table.
2656 Label* label = ins.first->second;
2657 if (!label->is_defined())
2659 label->define(location);
2664 error_at(location, "redefinition of label %qs",
2665 Gogo::message_name(label_name).c_str());
2666 inform(label->location(), "previous definition of %qs was here",
2667 Gogo::message_name(label_name).c_str());
2668 return new Label(label_name);
2673 // Add a reference to a label.
2676 Function::add_label_reference(const std::string& label_name)
2678 Label* lnull = NULL;
2679 std::pair<Labels::iterator, bool> ins =
2680 this->labels_.insert(std::make_pair(label_name, lnull));
2683 // The label was already in the hash table.
2684 return ins.first->second;
2688 gcc_assert(ins.first->second == NULL);
2689 Label* label = new Label(label_name);
2690 ins.first->second = label;
2695 // Swap one function with another. This is used when building the
2696 // thunk we use to call a function which calls recover. It may not
2697 // work for any other case.
2700 Function::swap_for_recover(Function *x)
2702 gcc_assert(this->enclosing_ == x->enclosing_);
2703 std::swap(this->named_results_, x->named_results_);
2704 std::swap(this->closure_var_, x->closure_var_);
2705 std::swap(this->block_, x->block_);
2706 gcc_assert(this->location_ == x->location_);
2707 gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2708 gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2711 // Traverse the tree.
2714 Function::traverse(Traverse* traverse)
2716 unsigned int traverse_mask = traverse->traverse_mask();
2719 & (Traverse::traverse_types | Traverse::traverse_expressions))
2722 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2723 return TRAVERSE_EXIT;
2726 // FIXME: We should check traverse_functions here if nested
2727 // functions are stored in block bindings.
2728 if (this->block_ != NULL
2730 & (Traverse::traverse_variables
2731 | Traverse::traverse_constants
2732 | Traverse::traverse_blocks
2733 | Traverse::traverse_statements
2734 | Traverse::traverse_expressions
2735 | Traverse::traverse_types)) != 0)
2737 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2738 return TRAVERSE_EXIT;
2741 return TRAVERSE_CONTINUE;
2744 // Work out types for unspecified variables and constants.
2747 Function::determine_types()
2749 if (this->block_ != NULL)
2750 this->block_->determine_types();
2753 // Export the function.
2756 Function::export_func(Export* exp, const std::string& name) const
2758 Function::export_func_with_type(exp, name, this->type_);
2761 // Export a function with a type.
2764 Function::export_func_with_type(Export* exp, const std::string& name,
2765 const Function_type* fntype)
2767 exp->write_c_string("func ");
2769 if (fntype->is_method())
2771 exp->write_c_string("(");
2772 exp->write_type(fntype->receiver()->type());
2773 exp->write_c_string(") ");
2776 exp->write_string(name);
2778 exp->write_c_string(" (");
2779 const Typed_identifier_list* parameters = fntype->parameters();
2780 if (parameters != NULL)
2782 bool is_varargs = fntype->is_varargs();
2784 for (Typed_identifier_list::const_iterator p = parameters->begin();
2785 p != parameters->end();
2791 exp->write_c_string(", ");
2792 if (!is_varargs || p + 1 != parameters->end())
2793 exp->write_type(p->type());
2796 exp->write_c_string("...");
2797 exp->write_type(p->type()->array_type()->element_type());
2801 exp->write_c_string(")");
2803 const Typed_identifier_list* results = fntype->results();
2804 if (results != NULL)
2806 if (results->size() == 1)
2808 exp->write_c_string(" ");
2809 exp->write_type(results->begin()->type());
2813 exp->write_c_string(" (");
2815 for (Typed_identifier_list::const_iterator p = results->begin();
2816 p != results->end();
2822 exp->write_c_string(", ");
2823 exp->write_type(p->type());
2825 exp->write_c_string(")");
2828 exp->write_c_string(";\n");
2831 // Import a function.
2834 Function::import_func(Import* imp, std::string* pname,
2835 Typed_identifier** preceiver,
2836 Typed_identifier_list** pparameters,
2837 Typed_identifier_list** presults,
2840 imp->require_c_string("func ");
2843 if (imp->peek_char() == '(')
2845 imp->require_c_string("(");
2846 Type* rtype = imp->read_type();
2847 *preceiver = new Typed_identifier(Import::import_marker, rtype,
2849 imp->require_c_string(") ");
2852 *pname = imp->read_identifier();
2854 Typed_identifier_list* parameters;
2855 *is_varargs = false;
2856 imp->require_c_string(" (");
2857 if (imp->peek_char() == ')')
2861 parameters = new Typed_identifier_list();
2864 if (imp->match_c_string("..."))
2870 Type* ptype = imp->read_type();
2872 ptype = Type::make_array_type(ptype, NULL);
2873 parameters->push_back(Typed_identifier(Import::import_marker,
2874 ptype, imp->location()));
2875 if (imp->peek_char() != ',')
2877 gcc_assert(!*is_varargs);
2878 imp->require_c_string(", ");
2881 imp->require_c_string(")");
2882 *pparameters = parameters;
2884 Typed_identifier_list* results;
2885 if (imp->peek_char() != ' ')
2889 results = new Typed_identifier_list();
2890 imp->require_c_string(" ");
2891 if (imp->peek_char() != '(')
2893 Type* rtype = imp->read_type();
2894 results->push_back(Typed_identifier(Import::import_marker, rtype,
2899 imp->require_c_string("(");
2902 Type* rtype = imp->read_type();
2903 results->push_back(Typed_identifier(Import::import_marker,
2904 rtype, imp->location()));
2905 if (imp->peek_char() != ',')
2907 imp->require_c_string(", ");
2909 imp->require_c_string(")");
2912 imp->require_c_string(";\n");
2913 *presults = results;
2918 Block::Block(Block* enclosing, source_location location)
2919 : enclosing_(enclosing), statements_(),
2920 bindings_(new Bindings(enclosing == NULL
2922 : enclosing->bindings())),
2923 start_location_(location),
2924 end_location_(UNKNOWN_LOCATION)
2928 // Add a statement to a block.
2931 Block::add_statement(Statement* statement)
2933 this->statements_.push_back(statement);
2936 // Add a statement to the front of a block. This is slow but is only
2937 // used for reference counts of parameters.
2940 Block::add_statement_at_front(Statement* statement)
2942 this->statements_.insert(this->statements_.begin(), statement);
2945 // Replace a statement in a block.
2948 Block::replace_statement(size_t index, Statement* s)
2950 gcc_assert(index < this->statements_.size());
2951 this->statements_[index] = s;
2954 // Add a statement before another statement.
2957 Block::insert_statement_before(size_t index, Statement* s)
2959 gcc_assert(index < this->statements_.size());
2960 this->statements_.insert(this->statements_.begin() + index, s);
2963 // Add a statement after another statement.
2966 Block::insert_statement_after(size_t index, Statement* s)
2968 gcc_assert(index < this->statements_.size());
2969 this->statements_.insert(this->statements_.begin() + index + 1, s);
2972 // Traverse the tree.
2975 Block::traverse(Traverse* traverse)
2977 unsigned int traverse_mask = traverse->traverse_mask();
2979 if ((traverse_mask & Traverse::traverse_blocks) != 0)
2981 int t = traverse->block(this);
2982 if (t == TRAVERSE_EXIT)
2983 return TRAVERSE_EXIT;
2984 else if (t == TRAVERSE_SKIP_COMPONENTS)
2985 return TRAVERSE_CONTINUE;
2989 & (Traverse::traverse_variables
2990 | Traverse::traverse_constants
2991 | Traverse::traverse_expressions
2992 | Traverse::traverse_types)) != 0)
2994 for (Bindings::const_definitions_iterator pb =
2995 this->bindings_->begin_definitions();
2996 pb != this->bindings_->end_definitions();
2999 switch ((*pb)->classification())
3001 case Named_object::NAMED_OBJECT_CONST:
3002 if ((traverse_mask & Traverse::traverse_constants) != 0)
3004 if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
3005 return TRAVERSE_EXIT;
3007 if ((traverse_mask & Traverse::traverse_types) != 0
3008 || (traverse_mask & Traverse::traverse_expressions) != 0)
3010 Type* t = (*pb)->const_value()->type();
3012 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3013 return TRAVERSE_EXIT;
3015 if ((traverse_mask & Traverse::traverse_expressions) != 0
3016 || (traverse_mask & Traverse::traverse_types) != 0)
3018 if ((*pb)->const_value()->traverse_expression(traverse)
3020 return TRAVERSE_EXIT;
3024 case Named_object::NAMED_OBJECT_VAR:
3025 case Named_object::NAMED_OBJECT_RESULT_VAR:
3026 if ((traverse_mask & Traverse::traverse_variables) != 0)
3028 if (traverse->variable(*pb) == TRAVERSE_EXIT)
3029 return TRAVERSE_EXIT;
3031 if (((traverse_mask & Traverse::traverse_types) != 0
3032 || (traverse_mask & Traverse::traverse_expressions) != 0)
3033 && ((*pb)->is_result_variable()
3034 || (*pb)->var_value()->has_type()))
3036 Type* t = ((*pb)->is_variable()
3037 ? (*pb)->var_value()->type()
3038 : (*pb)->result_var_value()->type());
3040 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3041 return TRAVERSE_EXIT;
3043 if ((*pb)->is_variable()
3044 && ((traverse_mask & Traverse::traverse_expressions) != 0
3045 || (traverse_mask & Traverse::traverse_types) != 0))
3047 if ((*pb)->var_value()->traverse_expression(traverse)
3049 return TRAVERSE_EXIT;
3053 case Named_object::NAMED_OBJECT_FUNC:
3054 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3055 // FIXME: Where will nested functions be found?
3058 case Named_object::NAMED_OBJECT_TYPE:
3059 if ((traverse_mask & Traverse::traverse_types) != 0
3060 || (traverse_mask & Traverse::traverse_expressions) != 0)
3062 if (Type::traverse((*pb)->type_value(), traverse)
3064 return TRAVERSE_EXIT;
3068 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3069 case Named_object::NAMED_OBJECT_UNKNOWN:
3072 case Named_object::NAMED_OBJECT_PACKAGE:
3073 case Named_object::NAMED_OBJECT_SINK:
3082 // No point in checking traverse_mask here--if we got here we always
3083 // want to walk the statements. The traversal can insert new
3084 // statements before or after the current statement. Inserting
3085 // statements before the current statement requires updating I via
3086 // the pointer; those statements will not be traversed. Any new
3087 // statements inserted after the current statement will be traversed
3089 for (size_t i = 0; i < this->statements_.size(); ++i)
3091 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3092 return TRAVERSE_EXIT;
3095 return TRAVERSE_CONTINUE;
3098 // Work out types for unspecified variables and constants.
3101 Block::determine_types()
3103 for (Bindings::const_definitions_iterator pb =
3104 this->bindings_->begin_definitions();
3105 pb != this->bindings_->end_definitions();
3108 if ((*pb)->is_variable())
3109 (*pb)->var_value()->determine_type();
3110 else if ((*pb)->is_const())
3111 (*pb)->const_value()->determine_type();
3114 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3115 ps != this->statements_.end();
3117 (*ps)->determine_types();
3120 // Return true if the statements in this block may fall through.
3123 Block::may_fall_through() const
3125 if (this->statements_.empty())
3127 return this->statements_.back()->may_fall_through();
3132 Variable::Variable(Type* type, Expression* init, bool is_global,
3133 bool is_parameter, bool is_receiver,
3134 source_location location)
3135 : type_(type), init_(init), preinit_(NULL), location_(location),
3136 is_global_(is_global), is_parameter_(is_parameter),
3137 is_receiver_(is_receiver), is_varargs_parameter_(false),
3138 is_address_taken_(false), seen_(false), init_is_lowered_(false),
3139 type_from_init_tuple_(false), type_from_range_index_(false),
3140 type_from_range_value_(false), type_from_chan_element_(false),
3141 is_type_switch_var_(false)
3143 gcc_assert(type != NULL || init != NULL);
3144 gcc_assert(!is_parameter || init == NULL);
3147 // Traverse the initializer expression.
3150 Variable::traverse_expression(Traverse* traverse)
3152 if (this->preinit_ != NULL)
3154 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3155 return TRAVERSE_EXIT;
3157 if (this->init_ != NULL)
3159 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3160 return TRAVERSE_EXIT;
3162 return TRAVERSE_CONTINUE;
3165 // Lower the initialization expression after parsing is complete.
3168 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3170 if (this->init_ != NULL && !this->init_is_lowered_)
3174 // We will give an error elsewhere, this is just to prevent
3175 // an infinite loop.
3180 gogo->lower_expression(function, &this->init_);
3182 this->seen_ = false;
3184 this->init_is_lowered_ = true;
3188 // Get the preinit block.
3191 Variable::preinit_block(Gogo* gogo)
3193 gcc_assert(this->is_global_);
3194 if (this->preinit_ == NULL)
3195 this->preinit_ = new Block(NULL, this->location());
3197 // If a global variable has a preinitialization statement, then we
3198 // need to have an initialization function.
3199 gogo->set_need_init_fn();
3201 return this->preinit_;
3204 // Add a statement to be run before the initialization expression.
3207 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3209 Block* b = this->preinit_block(gogo);
3210 b->add_statement(s);
3211 b->set_end_location(s->location());
3214 // In an assignment which sets a variable to a tuple of EXPR, return
3215 // the type of the first element of the tuple.
3218 Variable::type_from_tuple(Expression* expr, bool report_error) const
3220 if (expr->map_index_expression() != NULL)
3222 Map_type* mt = expr->map_index_expression()->get_map_type();
3224 return Type::make_error_type();
3225 return mt->val_type();
3227 else if (expr->receive_expression() != NULL)
3229 Expression* channel = expr->receive_expression()->channel();
3230 Type* channel_type = channel->type();
3231 if (channel_type->channel_type() == NULL)
3232 return Type::make_error_type();
3233 return channel_type->channel_type()->element_type();
3238 error_at(this->location(), "invalid tuple definition");
3239 return Type::make_error_type();
3243 // Given EXPR used in a range clause, return either the index type or
3244 // the value type of the range, depending upon GET_INDEX_TYPE.
3247 Variable::type_from_range(Expression* expr, bool get_index_type,
3248 bool report_error) const
3250 Type* t = expr->type();
3251 if (t->array_type() != NULL
3252 || (t->points_to() != NULL
3253 && t->points_to()->array_type() != NULL
3254 && !t->points_to()->is_open_array_type()))
3257 return Type::lookup_integer_type("int");
3259 return t->deref()->array_type()->element_type();
3261 else if (t->is_string_type())
3262 return Type::lookup_integer_type("int");
3263 else if (t->map_type() != NULL)
3266 return t->map_type()->key_type();
3268 return t->map_type()->val_type();
3270 else if (t->channel_type() != NULL)
3273 return t->channel_type()->element_type();
3277 error_at(this->location(),
3278 "invalid definition of value variable for channel range");
3279 return Type::make_error_type();
3285 error_at(this->location(), "invalid type for range clause");
3286 return Type::make_error_type();
3290 // EXPR should be a channel. Return the channel's element type.
3293 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3295 Type* t = expr->type();
3296 if (t->channel_type() != NULL)
3297 return t->channel_type()->element_type();
3301 error_at(this->location(), "expected channel");
3302 return Type::make_error_type();
3306 // Return the type of the Variable. This may be called before
3307 // Variable::determine_type is called, which means that we may need to
3308 // get the type from the initializer. FIXME: If we combine lowering
3309 // with type determination, then this should be unnecessary.
3314 // A variable in a type switch with a nil case will have the wrong
3315 // type here. This gets fixed up in determine_type, below.
3316 Type* type = this->type_;
3317 Expression* init = this->init_;
3318 if (this->is_type_switch_var_
3319 && this->type_->is_nil_constant_as_type())
3321 Type_guard_expression* tge = this->init_->type_guard_expression();
3322 gcc_assert(tge != NULL);
3329 if (this->type_ == NULL || !this->type_->is_error_type())
3331 error_at(this->location_, "variable initializer refers to itself");
3332 this->type_ = Type::make_error_type();
3341 else if (this->type_from_init_tuple_)
3342 type = this->type_from_tuple(init, false);
3343 else if (this->type_from_range_index_ || this->type_from_range_value_)
3344 type = this->type_from_range(init, this->type_from_range_index_, false);
3345 else if (this->type_from_chan_element_)
3346 type = this->type_from_chan_element(init, false);
3349 gcc_assert(init != NULL);
3350 type = init->type();
3351 gcc_assert(type != NULL);
3353 // Variables should not have abstract types.
3354 if (type->is_abstract())
3355 type = type->make_non_abstract_type();
3357 if (type->is_void_type())
3358 type = Type::make_error_type();
3361 this->seen_ = false;
3366 // Fetch the type from a const pointer, in which case it should have
3367 // been set already.
3370 Variable::type() const
3372 gcc_assert(this->type_ != NULL);
3376 // Set the type if necessary.
3379 Variable::determine_type()
3381 if (this->preinit_ != NULL)
3382 this->preinit_->determine_types();
3384 // A variable in a type switch with a nil case will have the wrong
3385 // type here. It will have an initializer which is a type guard.
3386 // We want to initialize it to the value without the type guard, and
3387 // use the type of that value as well.
3388 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3390 Type_guard_expression* tge = this->init_->type_guard_expression();
3391 gcc_assert(tge != NULL);
3393 this->init_ = tge->expr();
3396 if (this->init_ == NULL)
3397 gcc_assert(this->type_ != NULL && !this->type_->is_abstract());
3398 else if (this->type_from_init_tuple_)
3400 Expression *init = this->init_;
3401 init->determine_type_no_context();
3402 this->type_ = this->type_from_tuple(init, true);
3405 else if (this->type_from_range_index_ || this->type_from_range_value_)
3407 Expression* init = this->init_;
3408 init->determine_type_no_context();
3409 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3415 // type_from_chan_element_ should have been cleared during
3417 gcc_assert(!this->type_from_chan_element_);
3419 Type_context context(this->type_, false);
3420 this->init_->determine_type(&context);
3421 if (this->type_ == NULL)
3423 Type* type = this->init_->type();
3424 gcc_assert(type != NULL);
3425 if (type->is_abstract())
3426 type = type->make_non_abstract_type();
3428 if (type->is_void_type())
3430 error_at(this->location_, "variable has no type");
3431 type = Type::make_error_type();
3433 else if (type->is_nil_type())
3435 error_at(this->location_, "variable defined to nil type");
3436 type = Type::make_error_type();
3438 else if (type->is_call_multiple_result_type())
3440 error_at(this->location_,
3441 "single variable set to multiple value function call");
3442 type = Type::make_error_type();
3450 // Export the variable
3453 Variable::export_var(Export* exp, const std::string& name) const
3455 gcc_assert(this->is_global_);
3456 exp->write_c_string("var ");
3457 exp->write_string(name);
3458 exp->write_c_string(" ");
3459 exp->write_type(this->type());
3460 exp->write_c_string(";\n");
3463 // Import a variable.
3466 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3468 imp->require_c_string("var ");
3469 *pname = imp->read_identifier();
3470 imp->require_c_string(" ");
3471 *ptype = imp->read_type();
3472 imp->require_c_string(";\n");
3475 // Class Named_constant.
3477 // Traverse the initializer expression.
3480 Named_constant::traverse_expression(Traverse* traverse)
3482 return Expression::traverse(&this->expr_, traverse);
3485 // Determine the type of the constant.
3488 Named_constant::determine_type()
3490 if (this->type_ != NULL)
3492 Type_context context(this->type_, false);
3493 this->expr_->determine_type(&context);
3497 // A constant may have an abstract type.
3498 Type_context context(NULL, true);
3499 this->expr_->determine_type(&context);
3500 this->type_ = this->expr_->type();
3501 gcc_assert(this->type_ != NULL);
3505 // Indicate that we found and reported an error for this constant.
3508 Named_constant::set_error()
3510 this->type_ = Type::make_error_type();
3511 this->expr_ = Expression::make_error(this->location_);
3514 // Export a constant.
3517 Named_constant::export_const(Export* exp, const std::string& name) const
3519 exp->write_c_string("const ");
3520 exp->write_string(name);
3521 exp->write_c_string(" ");
3522 if (!this->type_->is_abstract())
3524 exp->write_type(this->type_);
3525 exp->write_c_string(" ");
3527 exp->write_c_string("= ");
3528 this->expr()->export_expression(exp);
3529 exp->write_c_string(";\n");
3532 // Import a constant.
3535 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3538 imp->require_c_string("const ");
3539 *pname = imp->read_identifier();
3540 imp->require_c_string(" ");
3541 if (imp->peek_char() == '=')
3545 *ptype = imp->read_type();
3546 imp->require_c_string(" ");
3548 imp->require_c_string("= ");
3549 *pexpr = Expression::import_expression(imp);
3550 imp->require_c_string(";\n");
3556 Type_declaration::add_method(const std::string& name, Function* function)
3558 Named_object* ret = Named_object::make_function(name, NULL, function);
3559 this->methods_.push_back(ret);
3563 // Add a method declaration.
3566 Type_declaration::add_method_declaration(const std::string& name,
3567 Function_type* type,
3568 source_location location)
3570 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3572 this->methods_.push_back(ret);
3576 // Return whether any methods ere defined.
3579 Type_declaration::has_methods() const
3581 return !this->methods_.empty();
3584 // Define methods for the real type.
3587 Type_declaration::define_methods(Named_type* nt)
3589 for (Methods::const_iterator p = this->methods_.begin();
3590 p != this->methods_.end();
3592 nt->add_existing_method(*p);
3595 // We are using the type. Return true if we should issue a warning.
3598 Type_declaration::using_type()
3600 bool ret = !this->issued_warning_;
3601 this->issued_warning_ = true;
3605 // Class Unknown_name.
3607 // Set the real named object.
3610 Unknown_name::set_real_named_object(Named_object* no)
3612 gcc_assert(this->real_named_object_ == NULL);
3613 gcc_assert(!no->is_unknown());
3614 this->real_named_object_ = no;
3617 // Class Named_object.
3619 Named_object::Named_object(const std::string& name,
3620 const Package* package,
3621 Classification classification)
3622 : name_(name), package_(package), classification_(classification),
3625 if (Gogo::is_sink_name(name))
3626 gcc_assert(classification == NAMED_OBJECT_SINK);
3629 // Make an unknown name. This is used by the parser. The name must
3630 // be resolved later. Unknown names are only added in the current
3634 Named_object::make_unknown_name(const std::string& name,
3635 source_location location)
3637 Named_object* named_object = new Named_object(name, NULL,
3638 NAMED_OBJECT_UNKNOWN);
3639 Unknown_name* value = new Unknown_name(location);
3640 named_object->u_.unknown_value = value;
3641 return named_object;
3647 Named_object::make_constant(const Typed_identifier& tid,
3648 const Package* package, Expression* expr,
3651 Named_object* named_object = new Named_object(tid.name(), package,
3652 NAMED_OBJECT_CONST);
3653 Named_constant* named_constant = new Named_constant(tid.type(), expr,
3656 named_object->u_.const_value = named_constant;
3657 return named_object;
3660 // Make a named type.
3663 Named_object::make_type(const std::string& name, const Package* package,
3664 Type* type, source_location location)
3666 Named_object* named_object = new Named_object(name, package,
3668 Named_type* named_type = Type::make_named_type(named_object, type, location);
3669 named_object->u_.type_value = named_type;
3670 return named_object;
3673 // Make a type declaration.
3676 Named_object::make_type_declaration(const std::string& name,
3677 const Package* package,
3678 source_location location)
3680 Named_object* named_object = new Named_object(name, package,
3681 NAMED_OBJECT_TYPE_DECLARATION);
3682 Type_declaration* type_declaration = new Type_declaration(location);
3683 named_object->u_.type_declaration = type_declaration;
3684 return named_object;
3690 Named_object::make_variable(const std::string& name, const Package* package,
3693 Named_object* named_object = new Named_object(name, package,
3695 named_object->u_.var_value = variable;
3696 return named_object;
3699 // Make a result variable.
3702 Named_object::make_result_variable(const std::string& name,
3703 Result_variable* result)
3705 Named_object* named_object = new Named_object(name, NULL,
3706 NAMED_OBJECT_RESULT_VAR);
3707 named_object->u_.result_var_value = result;
3708 return named_object;
3711 // Make a sink. This is used for the special blank identifier _.
3714 Named_object::make_sink()
3716 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
3719 // Make a named function.
3722 Named_object::make_function(const std::string& name, const Package* package,
3725 Named_object* named_object = new Named_object(name, package,
3727 named_object->u_.func_value = function;
3728 return named_object;
3731 // Make a function declaration.
3734 Named_object::make_function_declaration(const std::string& name,
3735 const Package* package,
3736 Function_type* fntype,
3737 source_location location)
3739 Named_object* named_object = new Named_object(name, package,
3740 NAMED_OBJECT_FUNC_DECLARATION);
3741 Function_declaration *func_decl = new Function_declaration(fntype, location);
3742 named_object->u_.func_declaration_value = func_decl;
3743 return named_object;
3749 Named_object::make_package(const std::string& alias, Package* package)
3751 Named_object* named_object = new Named_object(alias, NULL,
3752 NAMED_OBJECT_PACKAGE);
3753 named_object->u_.package_value = package;
3754 return named_object;
3757 // Return the name to use in an error message.
3760 Named_object::message_name() const
3762 if (this->package_ == NULL)
3763 return Gogo::message_name(this->name_);
3764 std::string ret = Gogo::message_name(this->package_->name());
3766 ret += Gogo::message_name(this->name_);
3770 // Set the type when a declaration is defined.
3773 Named_object::set_type_value(Named_type* named_type)
3775 gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
3776 Type_declaration* td = this->u_.type_declaration;
3777 td->define_methods(named_type);
3778 Named_object* in_function = td->in_function();
3779 if (in_function != NULL)
3780 named_type->set_in_function(in_function);
3782 this->classification_ = NAMED_OBJECT_TYPE;
3783 this->u_.type_value = named_type;
3786 // Define a function which was previously declared.
3789 Named_object::set_function_value(Function* function)
3791 gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
3792 this->classification_ = NAMED_OBJECT_FUNC;
3793 // FIXME: We should free the old value.
3794 this->u_.func_value = function;
3797 // Declare an unknown object as a type declaration.
3800 Named_object::declare_as_type()
3802 gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
3803 Unknown_name* unk = this->u_.unknown_value;
3804 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
3805 this->u_.type_declaration = new Type_declaration(unk->location());
3809 // Return the location of a named object.
3812 Named_object::location() const
3814 switch (this->classification_)
3817 case NAMED_OBJECT_UNINITIALIZED:
3820 case NAMED_OBJECT_UNKNOWN:
3821 return this->unknown_value()->location();
3823 case NAMED_OBJECT_CONST:
3824 return this->const_value()->location();
3826 case NAMED_OBJECT_TYPE:
3827 return this->type_value()->location();
3829 case NAMED_OBJECT_TYPE_DECLARATION:
3830 return this->type_declaration_value()->location();
3832 case NAMED_OBJECT_VAR:
3833 return this->var_value()->location();
3835 case NAMED_OBJECT_RESULT_VAR:
3836 return this->result_var_value()->function()->location();
3838 case NAMED_OBJECT_SINK:
3841 case NAMED_OBJECT_FUNC:
3842 return this->func_value()->location();
3844 case NAMED_OBJECT_FUNC_DECLARATION:
3845 return this->func_declaration_value()->location();
3847 case NAMED_OBJECT_PACKAGE:
3848 return this->package_value()->location();
3852 // Export a named object.
3855 Named_object::export_named_object(Export* exp) const
3857 switch (this->classification_)
3860 case NAMED_OBJECT_UNINITIALIZED:
3861 case NAMED_OBJECT_UNKNOWN:
3864 case NAMED_OBJECT_CONST:
3865 this->const_value()->export_const(exp, this->name_);
3868 case NAMED_OBJECT_TYPE:
3869 this->type_value()->export_named_type(exp, this->name_);
3872 case NAMED_OBJECT_TYPE_DECLARATION:
3873 error_at(this->type_declaration_value()->location(),
3874 "attempt to export %<%s%> which was declared but not defined",
3875 this->message_name().c_str());
3878 case NAMED_OBJECT_FUNC_DECLARATION:
3879 this->func_declaration_value()->export_func(exp, this->name_);
3882 case NAMED_OBJECT_VAR:
3883 this->var_value()->export_var(exp, this->name_);
3886 case NAMED_OBJECT_RESULT_VAR:
3887 case NAMED_OBJECT_SINK:
3890 case NAMED_OBJECT_FUNC:
3891 this->func_value()->export_func(exp, this->name_);
3898 Bindings::Bindings(Bindings* enclosing)
3899 : enclosing_(enclosing), named_objects_(), bindings_()
3906 Bindings::clear_file_scope()
3908 Contour::iterator p = this->bindings_.begin();
3909 while (p != this->bindings_.end())
3912 if (p->second->package() != NULL)
3914 else if (p->second->is_package())
3916 else if (p->second->is_function()
3917 && !p->second->func_value()->type()->is_method()
3918 && Gogo::unpack_hidden_name(p->second->name()) == "init")
3926 p = this->bindings_.erase(p);
3930 // Look up a symbol.
3933 Bindings::lookup(const std::string& name) const
3935 Contour::const_iterator p = this->bindings_.find(name);
3936 if (p != this->bindings_.end())
3937 return p->second->resolve();
3938 else if (this->enclosing_ != NULL)
3939 return this->enclosing_->lookup(name);
3944 // Look up a symbol locally.
3947 Bindings::lookup_local(const std::string& name) const
3949 Contour::const_iterator p = this->bindings_.find(name);
3950 if (p == this->bindings_.end())
3955 // Remove an object from a set of bindings. This is used for a
3956 // special case in thunks for functions which call recover.
3959 Bindings::remove_binding(Named_object* no)
3961 Contour::iterator pb = this->bindings_.find(no->name());
3962 gcc_assert(pb != this->bindings_.end());
3963 this->bindings_.erase(pb);
3964 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
3965 pn != this->named_objects_.end();
3970 this->named_objects_.erase(pn);
3977 // Add a method to the list of objects. This is not added to the
3978 // lookup table. This is so that we have a single list of objects
3979 // declared at the top level, which we walk through when it's time to
3980 // convert to trees.
3983 Bindings::add_method(Named_object* method)
3985 this->named_objects_.push_back(method);
3988 // Add a generic Named_object to a Contour.
3991 Bindings::add_named_object_to_contour(Contour* contour,
3992 Named_object* named_object)
3994 gcc_assert(named_object == named_object->resolve());
3995 const std::string& name(named_object->name());
3996 gcc_assert(!Gogo::is_sink_name(name));
3998 std::pair<Contour::iterator, bool> ins =
3999 contour->insert(std::make_pair(name, named_object));
4002 // The name was already there.
4003 if (named_object->package() != NULL
4004 && ins.first->second->package() == named_object->package()
4005 && (ins.first->second->classification()
4006 == named_object->classification()))
4008 // This is a second import of the same object.
4009 return ins.first->second;
4011 ins.first->second = this->new_definition(ins.first->second,
4013 return ins.first->second;
4017 // Don't push declarations on the list. We push them on when
4018 // and if we find the definitions. That way we genericize the
4019 // functions in order.
4020 if (!named_object->is_type_declaration()
4021 && !named_object->is_function_declaration()
4022 && !named_object->is_unknown())
4023 this->named_objects_.push_back(named_object);
4024 return named_object;
4028 // We had an existing named object OLD_OBJECT, and we've seen a new
4029 // one NEW_OBJECT with the same name. FIXME: This does not free the
4030 // new object when we don't need it.
4033 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4036 switch (old_object->classification())
4039 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4042 case Named_object::NAMED_OBJECT_UNKNOWN:
4044 Named_object* real = old_object->unknown_value()->real_named_object();
4046 return this->new_definition(real, new_object);
4047 gcc_assert(!new_object->is_unknown());
4048 old_object->unknown_value()->set_real_named_object(new_object);
4049 if (!new_object->is_type_declaration()
4050 && !new_object->is_function_declaration())
4051 this->named_objects_.push_back(new_object);
4055 case Named_object::NAMED_OBJECT_CONST:
4058 case Named_object::NAMED_OBJECT_TYPE:
4059 if (new_object->is_type_declaration())
4063 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4064 if (new_object->is_type_declaration())
4066 if (new_object->is_type())
4068 old_object->set_type_value(new_object->type_value());
4069 new_object->type_value()->set_named_object(old_object);
4070 this->named_objects_.push_back(old_object);
4075 case Named_object::NAMED_OBJECT_VAR:
4076 case Named_object::NAMED_OBJECT_RESULT_VAR:
4079 case Named_object::NAMED_OBJECT_SINK:
4082 case Named_object::NAMED_OBJECT_FUNC:
4083 if (new_object->is_function_declaration())
4085 if (!new_object->func_declaration_value()->asm_name().empty())
4086 sorry("__asm__ for function definitions");
4087 Function_type* old_type = old_object->func_value()->type();
4088 Function_type* new_type =
4089 new_object->func_declaration_value()->type();
4090 if (old_type->is_valid_redeclaration(new_type, &reason))
4095 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4097 Function_type* old_type = old_object->func_declaration_value()->type();
4098 if (new_object->is_function_declaration())
4100 Function_type* new_type =
4101 new_object->func_declaration_value()->type();
4102 if (old_type->is_valid_redeclaration(new_type, &reason))
4105 if (new_object->is_function())
4107 Function_type* new_type = new_object->func_value()->type();
4108 if (old_type->is_valid_redeclaration(new_type, &reason))
4110 if (!old_object->func_declaration_value()->asm_name().empty())
4111 sorry("__asm__ for function definitions");
4112 old_object->set_function_value(new_object->func_value());
4113 this->named_objects_.push_back(old_object);
4120 case Named_object::NAMED_OBJECT_PACKAGE:
4121 if (new_object->is_package()
4122 && (old_object->package_value()->name()
4123 == new_object->package_value()->name()))
4129 std::string n = old_object->message_name();
4131 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4133 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4136 inform(old_object->location(), "previous definition of %qs was here",
4142 // Add a named type.
4145 Bindings::add_named_type(Named_type* named_type)
4147 return this->add_named_object(named_type->named_object());
4153 Bindings::add_function(const std::string& name, const Package* package,
4156 return this->add_named_object(Named_object::make_function(name, package,
4160 // Add a function declaration.
4163 Bindings::add_function_declaration(const std::string& name,
4164 const Package* package,
4165 Function_type* type,
4166 source_location location)
4168 Named_object* no = Named_object::make_function_declaration(name, package,
4170 return this->add_named_object(no);
4173 // Define a type which was previously declared.
4176 Bindings::define_type(Named_object* no, Named_type* type)
4178 no->set_type_value(type);
4179 this->named_objects_.push_back(no);
4182 // Traverse bindings.
4185 Bindings::traverse(Traverse* traverse, bool is_global)
4187 unsigned int traverse_mask = traverse->traverse_mask();
4189 // We don't use an iterator because we permit the traversal to add
4190 // new global objects.
4191 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4193 Named_object* p = this->named_objects_[i];
4194 switch (p->classification())
4196 case Named_object::NAMED_OBJECT_CONST:
4197 if ((traverse_mask & Traverse::traverse_constants) != 0)
4199 if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4200 return TRAVERSE_EXIT;
4202 if ((traverse_mask & Traverse::traverse_types) != 0
4203 || (traverse_mask & Traverse::traverse_expressions) != 0)
4205 Type* t = p->const_value()->type();
4207 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4208 return TRAVERSE_EXIT;
4209 if (p->const_value()->traverse_expression(traverse)
4211 return TRAVERSE_EXIT;
4215 case Named_object::NAMED_OBJECT_VAR:
4216 case Named_object::NAMED_OBJECT_RESULT_VAR:
4217 if ((traverse_mask & Traverse::traverse_variables) != 0)
4219 if (traverse->variable(p) == TRAVERSE_EXIT)
4220 return TRAVERSE_EXIT;
4222 if (((traverse_mask & Traverse::traverse_types) != 0
4223 || (traverse_mask & Traverse::traverse_expressions) != 0)
4224 && (p->is_result_variable()
4225 || p->var_value()->has_type()))
4227 Type* t = (p->is_variable()
4228 ? p->var_value()->type()
4229 : p->result_var_value()->type());
4231 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4232 return TRAVERSE_EXIT;
4234 if (p->is_variable()
4235 && ((traverse_mask & Traverse::traverse_types) != 0
4236 || (traverse_mask & Traverse::traverse_expressions) != 0))
4238 if (p->var_value()->traverse_expression(traverse)
4240 return TRAVERSE_EXIT;
4244 case Named_object::NAMED_OBJECT_FUNC:
4245 if ((traverse_mask & Traverse::traverse_functions) != 0)
4247 int t = traverse->function(p);
4248 if (t == TRAVERSE_EXIT)
4249 return TRAVERSE_EXIT;
4250 else if (t == TRAVERSE_SKIP_COMPONENTS)
4255 & (Traverse::traverse_variables
4256 | Traverse::traverse_constants
4257 | Traverse::traverse_functions
4258 | Traverse::traverse_blocks
4259 | Traverse::traverse_statements
4260 | Traverse::traverse_expressions
4261 | Traverse::traverse_types)) != 0)
4263 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4264 return TRAVERSE_EXIT;
4268 case Named_object::NAMED_OBJECT_PACKAGE:
4269 // These are traversed in Gogo::traverse.
4270 gcc_assert(is_global);
4273 case Named_object::NAMED_OBJECT_TYPE:
4274 if ((traverse_mask & Traverse::traverse_types) != 0
4275 || (traverse_mask & Traverse::traverse_expressions) != 0)
4277 if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4278 return TRAVERSE_EXIT;
4282 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4283 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4284 case Named_object::NAMED_OBJECT_UNKNOWN:
4287 case Named_object::NAMED_OBJECT_SINK:
4293 return TRAVERSE_CONTINUE;
4298 Package::Package(const std::string& name, const std::string& unique_prefix,
4299 source_location location)
4300 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4301 priority_(0), location_(location), used_(false), is_imported_(false),
4302 uses_sink_alias_(false)
4304 gcc_assert(!name.empty() && !unique_prefix.empty());
4307 // Set the priority. We may see multiple priorities for an imported
4308 // package; we want to use the largest one.
4311 Package::set_priority(int priority)
4313 if (priority > this->priority_)
4314 this->priority_ = priority;
4317 // Determine types of constants. Everything else in a package
4318 // (variables, function declarations) should already have a fixed
4319 // type. Constants may have abstract types.
4322 Package::determine_types()
4324 Bindings* bindings = this->bindings_;
4325 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4326 p != bindings->end_definitions();
4329 if ((*p)->is_const())
4330 (*p)->const_value()->determine_type();
4338 Traverse::~Traverse()
4340 if (this->types_seen_ != NULL)
4341 delete this->types_seen_;
4342 if (this->expressions_seen_ != NULL)
4343 delete this->expressions_seen_;
4346 // Record that we are looking at a type, and return true if we have
4350 Traverse::remember_type(const Type* type)
4352 if (type->is_error_type())
4354 gcc_assert((this->traverse_mask() & traverse_types) != 0
4355 || (this->traverse_mask() & traverse_expressions) != 0);
4356 // We only have to remember named types, as they are the only ones
4357 // we can see multiple times in a traversal.
4358 if (type->classification() != Type::TYPE_NAMED)
4360 if (this->types_seen_ == NULL)
4361 this->types_seen_ = new Types_seen();
4362 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4366 // Record that we are looking at an expression, and return true if we
4367 // have already seen it.
4370 Traverse::remember_expression(const Expression* expression)
4372 gcc_assert((this->traverse_mask() & traverse_types) != 0
4373 || (this->traverse_mask() & traverse_expressions) != 0);
4374 if (this->expressions_seen_ == NULL)
4375 this->expressions_seen_ = new Expressions_seen();
4376 std::pair<Expressions_seen::iterator, bool> ins =
4377 this->expressions_seen_->insert(expression);
4381 // The default versions of these functions should never be called: the
4382 // traversal mask indicates which functions may be called.
4385 Traverse::variable(Named_object*)
4391 Traverse::constant(Named_object*, bool)
4397 Traverse::function(Named_object*)
4403 Traverse::block(Block*)
4409 Traverse::statement(Block*, size_t*, Statement*)
4415 Traverse::expression(Expression**)
4421 Traverse::type(Type*)