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 float_type_size, int pointer_size)
25 globals_(new Bindings(NULL)),
27 imported_unsafe_(false),
29 map_descriptors_(NULL),
30 type_descriptor_decls_(NULL),
38 const source_location loc = BUILTINS_LOCATION;
40 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
41 RUNTIME_TYPE_KIND_UINT8);
42 this->add_named_type(uint8_type);
43 this->add_named_type(Type::make_integer_type("uint16", true, 16,
44 RUNTIME_TYPE_KIND_UINT16));
45 this->add_named_type(Type::make_integer_type("uint32", true, 32,
46 RUNTIME_TYPE_KIND_UINT32));
47 this->add_named_type(Type::make_integer_type("uint64", true, 64,
48 RUNTIME_TYPE_KIND_UINT64));
50 this->add_named_type(Type::make_integer_type("int8", false, 8,
51 RUNTIME_TYPE_KIND_INT8));
52 this->add_named_type(Type::make_integer_type("int16", false, 16,
53 RUNTIME_TYPE_KIND_INT16));
54 this->add_named_type(Type::make_integer_type("int32", false, 32,
55 RUNTIME_TYPE_KIND_INT32));
56 this->add_named_type(Type::make_integer_type("int64", false, 64,
57 RUNTIME_TYPE_KIND_INT64));
59 this->add_named_type(Type::make_float_type("float32", 32,
60 RUNTIME_TYPE_KIND_FLOAT32));
61 this->add_named_type(Type::make_float_type("float64", 64,
62 RUNTIME_TYPE_KIND_FLOAT64));
64 this->add_named_type(Type::make_complex_type("complex64", 64,
65 RUNTIME_TYPE_KIND_COMPLEX64));
66 this->add_named_type(Type::make_complex_type("complex128", 128,
67 RUNTIME_TYPE_KIND_COMPLEX128));
69 if (int_type_size < 32)
71 this->add_named_type(Type::make_integer_type("uint", true,
73 RUNTIME_TYPE_KIND_UINT));
74 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
75 RUNTIME_TYPE_KIND_INT);
76 this->add_named_type(int_type);
78 // "byte" is an alias for "uint8". Construct a Named_object which
79 // points to UINT8_TYPE. Note that this breaks the normal pairing
80 // in which a Named_object points to a Named_type which points back
81 // to the same Named_object.
82 Named_object* byte_type = this->declare_type("byte", loc);
83 byte_type->set_type_value(uint8_type);
85 this->add_named_type(Type::make_integer_type("uintptr", true,
87 RUNTIME_TYPE_KIND_UINTPTR));
89 this->add_named_type(Type::make_float_type("float", float_type_size,
90 RUNTIME_TYPE_KIND_FLOAT));
92 this->add_named_type(Type::make_complex_type("complex", float_type_size * 2,
93 RUNTIME_TYPE_KIND_COMPLEX));
95 this->add_named_type(Type::make_named_bool_type());
97 this->add_named_type(Type::make_named_string_type());
99 this->globals_->add_constant(Typed_identifier("true",
100 Type::make_boolean_type(),
103 Expression::make_boolean(true, loc),
105 this->globals_->add_constant(Typed_identifier("false",
106 Type::make_boolean_type(),
109 Expression::make_boolean(false, loc),
112 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
115 Expression::make_nil(loc),
118 Type* abstract_int_type = Type::make_abstract_integer_type();
119 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
122 Expression::make_iota(),
125 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
126 new_type->set_is_varargs();
127 new_type->set_is_builtin();
128 this->globals_->add_function_declaration("new", NULL, new_type, loc);
130 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
131 make_type->set_is_varargs();
132 make_type->set_is_builtin();
133 this->globals_->add_function_declaration("make", NULL, make_type, loc);
135 Typed_identifier_list* len_result = new Typed_identifier_list();
136 len_result->push_back(Typed_identifier("", int_type, loc));
137 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
139 len_type->set_is_builtin();
140 this->globals_->add_function_declaration("len", NULL, len_type, loc);
142 Typed_identifier_list* cap_result = new Typed_identifier_list();
143 cap_result->push_back(Typed_identifier("", int_type, loc));
144 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
146 cap_type->set_is_builtin();
147 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
149 Function_type* 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("print", NULL, print_type, loc);
154 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
155 print_type->set_is_varargs();
156 print_type->set_is_builtin();
157 this->globals_->add_function_declaration("println", NULL, print_type, loc);
159 Type *empty = Type::make_interface_type(NULL, loc);
160 Typed_identifier_list* panic_parms = new Typed_identifier_list();
161 panic_parms->push_back(Typed_identifier("e", empty, loc));
162 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
164 panic_type->set_is_builtin();
165 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
167 Typed_identifier_list* recover_result = new Typed_identifier_list();
168 recover_result->push_back(Typed_identifier("", empty, loc));
169 Function_type* recover_type = Type::make_function_type(NULL, NULL,
172 recover_type->set_is_builtin();
173 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
175 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
176 close_type->set_is_varargs();
177 close_type->set_is_builtin();
178 this->globals_->add_function_declaration("close", NULL, close_type, loc);
180 Typed_identifier_list* closed_result = new Typed_identifier_list();
181 closed_result->push_back(Typed_identifier("", Type::lookup_bool_type(),
183 Function_type* closed_type = Type::make_function_type(NULL, NULL,
185 closed_type->set_is_varargs();
186 closed_type->set_is_builtin();
187 this->globals_->add_function_declaration("closed", NULL, closed_type, loc);
189 Typed_identifier_list* copy_result = new Typed_identifier_list();
190 copy_result->push_back(Typed_identifier("", int_type, loc));
191 Function_type* copy_type = Type::make_function_type(NULL, NULL,
193 copy_type->set_is_varargs();
194 copy_type->set_is_builtin();
195 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
197 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
198 append_type->set_is_varargs();
199 append_type->set_is_builtin();
200 this->globals_->add_function_declaration("append", NULL, append_type, loc);
202 Function_type* cmplx_type = Type::make_function_type(NULL, NULL, NULL, loc);
203 cmplx_type->set_is_varargs();
204 cmplx_type->set_is_builtin();
205 this->globals_->add_function_declaration("cmplx", NULL, cmplx_type, loc);
207 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
208 real_type->set_is_varargs();
209 real_type->set_is_builtin();
210 this->globals_->add_function_declaration("real", NULL, real_type, loc);
212 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
213 imag_type->set_is_varargs();
214 imag_type->set_is_builtin();
215 this->globals_->add_function_declaration("imag", NULL, cmplx_type, loc);
217 this->define_builtin_function_trees();
219 // Declare "init", to ensure that it is not defined with parameters
221 this->declare_function("init",
222 Type::make_function_type(NULL, NULL, NULL, loc),
226 // Munge name for use in an error message.
229 Gogo::message_name(const std::string& name)
231 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
234 // Get the package name.
237 Gogo::package_name() const
239 gcc_assert(this->package_ != NULL);
240 return this->package_->name();
243 // Set the package name.
246 Gogo::set_package_name(const std::string& package_name,
247 source_location location)
249 if (this->package_ != NULL && this->package_->name() != package_name)
251 error_at(location, "expected package %<%s%>",
252 Gogo::message_name(this->package_->name()).c_str());
256 // If the user did not specify a unique prefix, we always use "go".
257 // This in effect requires that the package name be unique.
258 if (this->unique_prefix_.empty())
259 this->unique_prefix_ = "go";
261 this->package_ = this->register_package(package_name, this->unique_prefix_,
264 // We used to permit people to qualify symbols with the current
265 // package name (e.g., P.x), but we no longer do.
266 // this->globals_->add_package(package_name, this->package_);
268 if (package_name == "main")
270 // Declare "main" as a function which takes no parameters and
272 this->declare_function("main",
273 Type::make_function_type(NULL, NULL, NULL,
282 Gogo::import_package(const std::string& filename,
283 const std::string& local_name,
284 bool is_local_name_exported,
285 source_location location)
287 if (filename == "unsafe")
289 this->import_unsafe(local_name, is_local_name_exported, location);
293 Imports::const_iterator p = this->imports_.find(filename);
294 if (p != this->imports_.end())
296 Package* package = p->second;
297 package->set_location(location);
298 package->set_is_imported();
299 std::string ln = local_name;
300 bool is_ln_exported = is_local_name_exported;
303 ln = package->name();
304 is_ln_exported = Lex::is_exported_name(ln);
308 ln = this->pack_hidden_name(ln, is_ln_exported);
309 this->package_->bindings()->add_package(ln, package);
313 Bindings* bindings = package->bindings();
314 for (Bindings::const_declarations_iterator p =
315 bindings->begin_declarations();
316 p != bindings->end_declarations();
318 this->add_named_object(p->second);
323 Import::Stream* stream = Import::open_package(filename, location);
326 error_at(location, "import file %qs not found", filename.c_str());
330 Import imp(stream, location);
331 imp.register_builtin_types(this);
332 Package* package = imp.import(this, local_name, is_local_name_exported);
335 this->imports_.insert(std::make_pair(filename, package));
336 package->set_is_imported();
342 // Add an import control function for an imported package to the list.
345 Gogo::add_import_init_fn(const std::string& package_name,
346 const std::string& init_name, int prio)
348 for (std::set<Import_init>::const_iterator p =
349 this->imported_init_fns_.begin();
350 p != this->imported_init_fns_.end();
353 if (p->init_name() == init_name
354 && (p->package_name() != package_name || p->priority() != prio))
356 error("duplicate package initialization name %qs",
357 Gogo::message_name(init_name).c_str());
358 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
359 Gogo::message_name(p->package_name()).c_str(),
361 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
362 Gogo::message_name(package_name).c_str(), prio);
367 this->imported_init_fns_.insert(Import_init(package_name, init_name,
371 // Return whether we are at the global binding level.
374 Gogo::in_global_scope() const
376 return this->functions_.empty();
379 // Return the current binding contour.
382 Gogo::current_bindings()
384 if (!this->functions_.empty())
385 return this->functions_.back().blocks.back()->bindings();
386 else if (this->package_ != NULL)
387 return this->package_->bindings();
389 return this->globals_;
393 Gogo::current_bindings() const
395 if (!this->functions_.empty())
396 return this->functions_.back().blocks.back()->bindings();
397 else if (this->package_ != NULL)
398 return this->package_->bindings();
400 return this->globals_;
403 // Return the current block.
406 Gogo::current_block()
408 if (this->functions_.empty())
411 return this->functions_.back().blocks.back();
414 // Look up a name in the current binding contour. If PFUNCTION is not
415 // NULL, set it to the function in which the name is defined, or NULL
416 // if the name is defined in global scope.
419 Gogo::lookup(const std::string& name, Named_object** pfunction) const
421 if (pfunction != NULL)
424 if (Gogo::is_sink_name(name))
425 return Named_object::make_sink();
427 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
428 p != this->functions_.rend();
431 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
434 if (pfunction != NULL)
435 *pfunction = p->function;
440 if (this->package_ != NULL)
442 Named_object* ret = this->package_->bindings()->lookup(name);
445 if (ret->package() != NULL)
446 ret->package()->set_used();
451 // We do not look in the global namespace. If we did, the global
452 // namespace would effectively hide names which were defined in
453 // package scope which we have not yet seen. Instead,
454 // define_global_names is called after parsing is over to connect
455 // undefined names at package scope with names defined at global
461 // Look up a name in the current block, without searching enclosing
465 Gogo::lookup_in_block(const std::string& name) const
467 gcc_assert(!this->functions_.empty());
468 gcc_assert(!this->functions_.back().blocks.empty());
469 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
472 // Look up a name in the global namespace.
475 Gogo::lookup_global(const char* name) const
477 return this->globals_->lookup(name);
480 // Add an imported package.
483 Gogo::add_imported_package(const std::string& real_name,
484 const std::string& alias_arg,
485 bool is_alias_exported,
486 const std::string& unique_prefix,
487 source_location location,
488 bool* padd_to_globals)
490 // FIXME: Now that we compile packages as a whole, should we permit
491 // importing the current package?
492 if (this->package_name() == real_name
493 && this->unique_prefix() == unique_prefix)
495 *padd_to_globals = false;
496 if (!alias_arg.empty() && alias_arg != ".")
498 std::string alias = this->pack_hidden_name(alias_arg,
500 this->package_->bindings()->add_package(alias, this->package_);
502 return this->package_;
504 else if (alias_arg == ".")
506 *padd_to_globals = true;
507 return this->register_package(real_name, unique_prefix, location);
509 else if (alias_arg == "_")
511 Package* ret = this->register_package(real_name, unique_prefix, location);
512 ret->set_uses_sink_alias();
517 *padd_to_globals = false;
518 std::string alias = alias_arg;
522 is_alias_exported = Lex::is_exported_name(alias);
524 alias = this->pack_hidden_name(alias, is_alias_exported);
525 Named_object* no = this->add_package(real_name, alias, unique_prefix,
527 if (!no->is_package())
529 return no->package_value();
536 Gogo::add_package(const std::string& real_name, const std::string& alias,
537 const std::string& unique_prefix, source_location location)
539 gcc_assert(this->in_global_scope());
541 // Register the package. Note that we might have already seen it in
542 // an earlier import.
543 Package* package = this->register_package(real_name, unique_prefix, location);
545 return this->package_->bindings()->add_package(alias, package);
548 // Register a package. This package may or may not be imported. This
549 // returns the Package structure for the package, creating if it
553 Gogo::register_package(const std::string& package_name,
554 const std::string& unique_prefix,
555 source_location location)
557 gcc_assert(!unique_prefix.empty() && !package_name.empty());
558 std::string name = unique_prefix + '.' + package_name;
559 Package* package = NULL;
560 std::pair<Packages::iterator, bool> ins =
561 this->packages_.insert(std::make_pair(name, package));
564 // We have seen this package name before.
565 package = ins.first->second;
566 gcc_assert(package != NULL);
567 gcc_assert(package->name() == package_name
568 && package->unique_prefix() == unique_prefix);
569 if (package->location() == UNKNOWN_LOCATION)
570 package->set_location(location);
574 // First time we have seen this package name.
575 package = new Package(package_name, unique_prefix, location);
576 gcc_assert(ins.first->second == NULL);
577 ins.first->second = package;
583 // Start compiling a function.
586 Gogo::start_function(const std::string& name, Function_type* type,
587 bool add_method_to_type, source_location location)
589 bool at_top_level = this->functions_.empty();
591 Block* block = new Block(NULL, location);
593 Function* enclosing = (at_top_level
595 : this->functions_.back().function->func_value());
597 Function* function = new Function(type, enclosing, block, location);
599 if (type->is_method())
601 const Typed_identifier* receiver = type->receiver();
602 Variable* this_param = new Variable(receiver->type(), NULL, false,
603 true, true, location);
604 std::string name = receiver->name();
607 // We need to give receivers a name since they wind up in
608 // DECL_ARGUMENTS. FIXME.
609 static unsigned int count;
611 snprintf(buf, sizeof buf, "r.%u", count);
615 block->bindings()->add_variable(name, NULL, this_param);
618 const Typed_identifier_list* parameters = type->parameters();
619 bool is_varargs = type->is_varargs();
620 if (parameters != NULL)
622 for (Typed_identifier_list::const_iterator p = parameters->begin();
623 p != parameters->end();
626 Variable* param = new Variable(p->type(), NULL, false, true, false,
628 if (is_varargs && p + 1 == parameters->end())
629 param->set_is_varargs_parameter();
631 std::string name = p->name();
632 if (name.empty() || Gogo::is_sink_name(name))
634 // We need to give parameters a name since they wind up
635 // in DECL_ARGUMENTS. FIXME.
636 static unsigned int count;
638 snprintf(buf, sizeof buf, "p.%u", count);
642 block->bindings()->add_variable(name, NULL, param);
646 function->create_named_result_variables(this);
648 const std::string* pname;
649 std::string nested_name;
654 // Invent a name for a nested function.
655 static int nested_count;
657 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
660 pname = &nested_name;
664 if (Gogo::is_sink_name(*pname))
666 static int sink_count;
668 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
670 ret = Named_object::make_function(buf, NULL, function);
672 else if (!type->is_method())
674 ret = this->package_->bindings()->add_function(*pname, NULL, function);
675 if (!ret->is_function())
677 // Redefinition error.
678 ret = Named_object::make_function(name, NULL, function);
683 if (!add_method_to_type)
684 ret = Named_object::make_function(name, NULL, function);
687 gcc_assert(at_top_level);
688 Type* rtype = type->receiver()->type();
690 // We want to look through the pointer created by the
691 // parser, without getting an error if the type is not yet
693 if (rtype->classification() == Type::TYPE_POINTER)
694 rtype = rtype->points_to();
696 if (rtype->is_error_type())
697 ret = Named_object::make_function(name, NULL, function);
698 else if (rtype->named_type() != NULL)
700 ret = rtype->named_type()->add_method(name, function);
701 if (!ret->is_function())
703 // Redefinition error.
704 ret = Named_object::make_function(name, NULL, function);
707 else if (rtype->forward_declaration_type() != NULL)
709 Named_object* type_no =
710 rtype->forward_declaration_type()->named_object();
711 if (type_no->is_unknown())
713 // If we are seeing methods it really must be a
714 // type. Declare it as such. An alternative would
715 // be to support lists of methods for unknown
716 // expressions. Either way the error messages if
717 // this is not a type are going to get confusing.
718 Named_object* declared =
719 this->declare_package_type(type_no->name(),
720 type_no->location());
722 == type_no->unknown_value()->real_named_object());
724 ret = rtype->forward_declaration_type()->add_method(name,
730 this->package_->bindings()->add_method(ret);
733 this->functions_.resize(this->functions_.size() + 1);
734 Open_function& of(this->functions_.back());
736 of.blocks.push_back(block);
738 if (!type->is_method() && Gogo::unpack_hidden_name(name) == "init")
740 this->init_functions_.push_back(ret);
741 this->need_init_fn_ = true;
747 // Finish compiling a function.
750 Gogo::finish_function(source_location location)
752 this->finish_block(location);
753 gcc_assert(this->functions_.back().blocks.empty());
754 this->functions_.pop_back();
757 // Return the current function.
760 Gogo::current_function() const
762 gcc_assert(!this->functions_.empty());
763 return this->functions_.back().function;
766 // Start a new block.
769 Gogo::start_block(source_location location)
771 gcc_assert(!this->functions_.empty());
772 Block* block = new Block(this->current_block(), location);
773 this->functions_.back().blocks.push_back(block);
779 Gogo::finish_block(source_location location)
781 gcc_assert(!this->functions_.empty());
782 gcc_assert(!this->functions_.back().blocks.empty());
783 Block* block = this->functions_.back().blocks.back();
784 this->functions_.back().blocks.pop_back();
785 block->set_end_location(location);
789 // Add an unknown name.
792 Gogo::add_unknown_name(const std::string& name, source_location location)
794 return this->package_->bindings()->add_unknown_name(name, location);
797 // Declare a function.
800 Gogo::declare_function(const std::string& name, Function_type* type,
801 source_location location)
803 if (!type->is_method())
804 return this->current_bindings()->add_function_declaration(name, NULL, type,
808 // We don't bother to add this to the list of global
810 Type* rtype = type->receiver()->type();
812 // We want to look through the pointer created by the
813 // parser, without getting an error if the type is not yet
815 if (rtype->classification() == Type::TYPE_POINTER)
816 rtype = rtype->points_to();
818 if (rtype->is_error_type())
820 else if (rtype->named_type() != NULL)
821 return rtype->named_type()->add_method_declaration(name, NULL, type,
823 else if (rtype->forward_declaration_type() != NULL)
825 Forward_declaration_type* ftype = rtype->forward_declaration_type();
826 return ftype->add_method_declaration(name, type, location);
833 // Add a label definition.
836 Gogo::add_label_definition(const std::string& label_name,
837 source_location location)
839 gcc_assert(!this->functions_.empty());
840 Function* func = this->functions_.back().function->func_value();
841 Label* label = func->add_label_definition(label_name, location);
842 this->add_statement(Statement::make_label_statement(label, location));
846 // Add a label reference.
849 Gogo::add_label_reference(const std::string& label_name)
851 gcc_assert(!this->functions_.empty());
852 Function* func = this->functions_.back().function->func_value();
853 return func->add_label_reference(label_name);
859 Gogo::add_statement(Statement* statement)
861 gcc_assert(!this->functions_.empty()
862 && !this->functions_.back().blocks.empty());
863 this->functions_.back().blocks.back()->add_statement(statement);
869 Gogo::add_block(Block* block, source_location location)
871 gcc_assert(!this->functions_.empty()
872 && !this->functions_.back().blocks.empty());
873 Statement* statement = Statement::make_block_statement(block, location);
874 this->functions_.back().blocks.back()->add_statement(statement);
880 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
883 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
889 Gogo::add_type(const std::string& name, Type* type, source_location location)
891 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
893 if (!this->in_global_scope() && no->is_type())
894 no->type_value()->set_in_function(this->functions_.back().function);
900 Gogo::add_named_type(Named_type* type)
902 gcc_assert(this->in_global_scope());
903 this->current_bindings()->add_named_type(type);
909 Gogo::declare_type(const std::string& name, source_location location)
911 Bindings* bindings = this->current_bindings();
912 Named_object* no = bindings->add_type_declaration(name, NULL, location);
913 if (!this->in_global_scope() && no->is_type_declaration())
915 Named_object* f = this->functions_.back().function;
916 no->type_declaration_value()->set_in_function(f);
921 // Declare a type at the package level.
924 Gogo::declare_package_type(const std::string& name, source_location location)
926 return this->package_->bindings()->add_type_declaration(name, NULL, location);
929 // Define a type which was already declared.
932 Gogo::define_type(Named_object* no, Named_type* type)
934 this->current_bindings()->define_type(no, type);
940 Gogo::add_variable(const std::string& name, Variable* variable)
942 Named_object* no = this->current_bindings()->add_variable(name, NULL,
945 // In a function the middle-end wants to see a DECL_EXPR node.
948 && !no->var_value()->is_parameter()
949 && !this->functions_.empty())
950 this->add_statement(Statement::make_variable_declaration(no));
955 // Add a sink--a reference to the blank identifier _.
960 return Named_object::make_sink();
963 // Add a named object.
966 Gogo::add_named_object(Named_object* no)
968 this->current_bindings()->add_named_object(no);
971 // Record that we've seen an interface type.
974 Gogo::record_interface_type(Interface_type* itype)
976 this->interface_types_.push_back(itype);
979 // Return a name for a thunk object.
984 static int thunk_count;
986 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
991 // Return whether a function is a thunk.
994 Gogo::is_thunk(const Named_object* no)
996 return no->name().compare(0, 6, "$thunk") == 0;
999 // Define the global names. We do this only after parsing all the
1000 // input files, because the program might define the global names
1004 Gogo::define_global_names()
1006 for (Bindings::const_declarations_iterator p =
1007 this->globals_->begin_declarations();
1008 p != this->globals_->end_declarations();
1011 Named_object* global_no = p->second;
1012 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1013 Named_object* no = this->package_->bindings()->lookup(name);
1017 if (no->is_type_declaration())
1019 if (global_no->is_type())
1021 if (no->type_declaration_value()->has_methods())
1022 error_at(no->location(),
1023 "may not define methods for global type");
1024 no->set_type_value(global_no->type_value());
1028 error_at(no->location(), "expected type");
1029 Type* errtype = Type::make_error_type();
1030 Named_object* err = Named_object::make_type("error", NULL,
1033 no->set_type_value(err->type_value());
1036 else if (no->is_unknown())
1037 no->unknown_value()->set_real_named_object(global_no);
1041 // Clear out names in file scope.
1044 Gogo::clear_file_scope()
1046 this->package_->bindings()->clear_file_scope();
1048 // Warn about packages which were imported but not used.
1049 for (Packages::iterator p = this->packages_.begin();
1050 p != this->packages_.end();
1053 Package* package = p->second;
1054 if (package != this->package_
1055 && package->is_imported()
1057 && !package->uses_sink_alias()
1059 error_at(package->location(), "imported and not used: %s",
1060 Gogo::message_name(package->name()).c_str());
1061 package->clear_is_imported();
1062 package->clear_uses_sink_alias();
1063 package->clear_used();
1067 // Traverse the tree.
1070 Gogo::traverse(Traverse* traverse)
1072 // Traverse the current package first for consistency. The other
1073 // packages will only contain imported types, constants, and
1075 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1077 for (Packages::const_iterator p = this->packages_.begin();
1078 p != this->packages_.end();
1081 if (p->second != this->package_)
1083 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1089 // Traversal class used to verify types.
1091 class Verify_types : public Traverse
1095 : Traverse(traverse_types)
1102 // Verify that a type is correct.
1105 Verify_types::type(Type* t)
1107 // Don't verify types defined in other packages.
1108 Named_type* nt = t->named_type();
1109 if (nt != NULL && nt->named_object()->package() != NULL)
1110 return TRAVERSE_SKIP_COMPONENTS;
1113 return TRAVERSE_SKIP_COMPONENTS;
1114 return TRAVERSE_CONTINUE;
1117 // Verify that all types are correct.
1120 Gogo::verify_types()
1122 Verify_types traverse;
1123 this->traverse(&traverse);
1126 // Traversal class used to lower parse tree.
1128 class Lower_parse_tree : public Traverse
1131 Lower_parse_tree(Gogo* gogo, Named_object* function)
1132 : Traverse(traverse_constants
1133 | traverse_functions
1134 | traverse_statements
1135 | traverse_expressions),
1136 gogo_(gogo), function_(function), iota_value_(-1)
1140 constant(Named_object*, bool);
1143 function(Named_object*);
1146 statement(Block*, size_t* pindex, Statement*);
1149 expression(Expression**);
1154 // The function we are traversing.
1155 Named_object* function_;
1156 // Value to use for the predeclared constant iota.
1160 // Lower constants. We handle constants specially so that we can set
1161 // the right value for the predeclared constant iota. This works in
1162 // conjunction with the way we lower Const_expression objects.
1165 Lower_parse_tree::constant(Named_object* no, bool)
1167 Named_constant* nc = no->const_value();
1169 // Don't get into trouble if the constant's initializer expression
1170 // refers to the constant itself.
1172 return TRAVERSE_CONTINUE;
1175 gcc_assert(this->iota_value_ == -1);
1176 this->iota_value_ = nc->iota_value();
1177 nc->traverse_expression(this);
1178 this->iota_value_ = -1;
1180 nc->clear_lowering();
1182 // We will traverse the expression a second time, but that will be
1185 return TRAVERSE_CONTINUE;
1188 // Lower function closure types. Record the function while lowering
1189 // it, so that we can pass it down when lowering an expression.
1192 Lower_parse_tree::function(Named_object* no)
1194 no->func_value()->set_closure_type();
1196 gcc_assert(this->function_ == NULL);
1197 this->function_ = no;
1198 int t = no->func_value()->traverse(this);
1199 this->function_ = NULL;
1201 if (t == TRAVERSE_EXIT)
1203 return TRAVERSE_SKIP_COMPONENTS;
1206 // Lower statement parse trees.
1209 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1211 // Lower the expressions first.
1212 int t = sorig->traverse_contents(this);
1213 if (t == TRAVERSE_EXIT)
1216 // Keep lowering until nothing changes.
1217 Statement* s = sorig;
1220 Statement* snew = s->lower(this->gogo_, block);
1224 t = s->traverse_contents(this);
1225 if (t == TRAVERSE_EXIT)
1230 block->replace_statement(*pindex, s);
1232 return TRAVERSE_SKIP_COMPONENTS;
1235 // Lower expression parse trees.
1238 Lower_parse_tree::expression(Expression** pexpr)
1240 // We have to lower all subexpressions first, so that we can get
1241 // their type if necessary. This is awkward, because we don't have
1242 // a postorder traversal pass.
1243 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1244 return TRAVERSE_EXIT;
1245 // Keep lowering until nothing changes.
1248 Expression* e = *pexpr;
1249 Expression* enew = e->lower(this->gogo_, this->function_,
1255 return TRAVERSE_SKIP_COMPONENTS;
1258 // Lower the parse tree. This is called after the parse is complete,
1259 // when all names should be resolved.
1262 Gogo::lower_parse_tree()
1264 Lower_parse_tree lower_parse_tree(this, NULL);
1265 this->traverse(&lower_parse_tree);
1268 // Lower an expression.
1271 Gogo::lower_expression(Named_object* function, Expression** pexpr)
1273 Lower_parse_tree lower_parse_tree(this, function);
1274 lower_parse_tree.expression(pexpr);
1277 // Lower a constant. This is called when lowering a reference to a
1278 // constant. We have to make sure that the constant has already been
1282 Gogo::lower_constant(Named_object* no)
1284 gcc_assert(no->is_const());
1285 Lower_parse_tree lower(this, NULL);
1286 lower.constant(no, false);
1289 // Look for interface types to finalize methods of inherited
1292 class Finalize_methods : public Traverse
1295 Finalize_methods(Gogo* gogo)
1296 : Traverse(traverse_types),
1307 // Finalize the methods of an interface type.
1310 Finalize_methods::type(Type* t)
1312 // Check the classification so that we don't finalize the methods
1313 // twice for a named interface type.
1314 switch (t->classification())
1316 case Type::TYPE_INTERFACE:
1317 t->interface_type()->finalize_methods();
1320 case Type::TYPE_NAMED:
1322 // We have to finalize the methods of the real type first.
1323 // But if the real type is a struct type, then we only want to
1324 // finalize the methods of the field types, not of the struct
1325 // type itself. We don't want to add methods to the struct,
1326 // since it has a name.
1327 Type* rt = t->named_type()->real_type();
1328 if (rt->classification() != Type::TYPE_STRUCT)
1330 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1331 return TRAVERSE_EXIT;
1335 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1336 return TRAVERSE_EXIT;
1339 t->named_type()->finalize_methods(this->gogo_);
1341 return TRAVERSE_SKIP_COMPONENTS;
1344 case Type::TYPE_STRUCT:
1345 t->struct_type()->finalize_methods(this->gogo_);
1352 return TRAVERSE_CONTINUE;
1355 // Finalize method lists and build stub methods for types.
1358 Gogo::finalize_methods()
1360 Finalize_methods finalize(this);
1361 this->traverse(&finalize);
1364 // Set types for unspecified variables and constants.
1367 Gogo::determine_types()
1369 Bindings* bindings = this->current_bindings();
1370 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1371 p != bindings->end_definitions();
1374 if ((*p)->is_function())
1375 (*p)->func_value()->determine_types();
1376 else if ((*p)->is_variable())
1377 (*p)->var_value()->determine_type();
1378 else if ((*p)->is_const())
1379 (*p)->const_value()->determine_type();
1381 // See if a variable requires us to build an initialization
1382 // function. We know that we will see all global variables
1384 if (!this->need_init_fn_ && (*p)->is_variable())
1386 Variable* variable = (*p)->var_value();
1388 // If this is a global variable which requires runtime
1389 // initialization, we need an initialization function.
1390 if (!variable->is_global())
1392 else if (variable->has_pre_init())
1393 this->need_init_fn_ = true;
1394 else if (variable->init() == NULL)
1396 else if (variable->type()->interface_type() != NULL)
1397 this->need_init_fn_ = true;
1398 else if (variable->init()->is_constant())
1400 else if (!variable->init()->is_composite_literal())
1401 this->need_init_fn_ = true;
1402 else if (variable->init()->is_nonconstant_composite_literal())
1403 this->need_init_fn_ = true;
1405 // If this is a global variable which holds a pointer value,
1406 // then we need an initialization function to register it as a
1408 if (variable->is_global() && variable->type()->has_pointer())
1409 this->need_init_fn_ = true;
1413 // Determine the types of constants in packages.
1414 for (Packages::const_iterator p = this->packages_.begin();
1415 p != this->packages_.end();
1417 p->second->determine_types();
1420 // Traversal class used for type checking.
1422 class Check_types_traverse : public Traverse
1425 Check_types_traverse(Gogo* gogo)
1426 : Traverse(traverse_variables
1427 | traverse_constants
1428 | traverse_statements
1429 | traverse_expressions),
1434 variable(Named_object*);
1437 constant(Named_object*, bool);
1440 statement(Block*, size_t* pindex, Statement*);
1443 expression(Expression**);
1450 // Check that a variable initializer has the right type.
1453 Check_types_traverse::variable(Named_object* named_object)
1455 if (named_object->is_variable())
1457 Variable* var = named_object->var_value();
1458 Expression* init = var->init();
1461 && !Type::are_assignable(var->type(), init->type(), &reason))
1464 error_at(var->location(), "incompatible type in initialization");
1466 error_at(var->location(),
1467 "incompatible type in initialization (%s)",
1472 return TRAVERSE_CONTINUE;
1475 // Check that a constant initializer has the right type.
1478 Check_types_traverse::constant(Named_object* named_object, bool)
1480 Named_constant* constant = named_object->const_value();
1481 Type* ctype = constant->type();
1482 if (ctype->integer_type() == NULL
1483 && ctype->float_type() == NULL
1484 && ctype->complex_type() == NULL
1485 && !ctype->is_boolean_type()
1486 && !ctype->is_string_type())
1488 if (!ctype->is_error_type())
1489 error_at(constant->location(), "invalid constant type");
1490 constant->set_error();
1492 else if (!constant->expr()->is_constant())
1494 error_at(constant->expr()->location(), "expression is not constant");
1495 constant->set_error();
1497 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1500 error_at(constant->location(),
1501 "initialization expression has wrong type");
1502 constant->set_error();
1504 return TRAVERSE_CONTINUE;
1507 // Check that types are valid in a statement.
1510 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1512 s->check_types(this->gogo_);
1513 return TRAVERSE_CONTINUE;
1516 // Check that types are valid in an expression.
1519 Check_types_traverse::expression(Expression** expr)
1521 (*expr)->check_types(this->gogo_);
1522 return TRAVERSE_CONTINUE;
1525 // Check that types are valid.
1530 Check_types_traverse traverse(this);
1531 this->traverse(&traverse);
1534 // Check the types in a single block.
1537 Gogo::check_types_in_block(Block* block)
1539 Check_types_traverse traverse(this);
1540 block->traverse(&traverse);
1543 // A traversal class used to find a single shortcut operator within an
1546 class Find_shortcut : public Traverse
1550 : Traverse(traverse_blocks
1551 | traverse_statements
1552 | traverse_expressions),
1556 // A pointer to the expression which was found, or NULL if none was
1560 { return this->found_; }
1565 { return TRAVERSE_SKIP_COMPONENTS; }
1568 statement(Block*, size_t*, Statement*)
1569 { return TRAVERSE_SKIP_COMPONENTS; }
1572 expression(Expression**);
1575 Expression** found_;
1578 // Find a shortcut expression.
1581 Find_shortcut::expression(Expression** pexpr)
1583 Expression* expr = *pexpr;
1584 Binary_expression* be = expr->binary_expression();
1586 return TRAVERSE_CONTINUE;
1587 Operator op = be->op();
1588 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1589 return TRAVERSE_CONTINUE;
1590 gcc_assert(this->found_ == NULL);
1591 this->found_ = pexpr;
1592 return TRAVERSE_EXIT;
1595 // A traversal class used to turn shortcut operators into explicit if
1598 class Shortcuts : public Traverse
1602 : Traverse(traverse_variables
1603 | traverse_statements)
1608 variable(Named_object*);
1611 statement(Block*, size_t*, Statement*);
1614 // Convert a shortcut operator.
1616 convert_shortcut(Block* enclosing, Expression** pshortcut);
1619 // Remove shortcut operators in a single statement.
1622 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1624 // FIXME: This approach doesn't work for switch statements, because
1625 // we add the new statements before the whole switch when we need to
1626 // instead add them just before the switch expression. The right
1627 // fix is probably to lower switch statements with nonconstant cases
1628 // to a series of conditionals.
1629 if (s->switch_statement() != NULL)
1630 return TRAVERSE_CONTINUE;
1634 Find_shortcut find_shortcut;
1636 // If S is a variable declaration, then ordinary traversal won't
1637 // do anything. We want to explicitly traverse the
1638 // initialization expression if there is one.
1639 Variable_declaration_statement* vds = s->variable_declaration_statement();
1640 Expression* init = NULL;
1642 s->traverse_contents(&find_shortcut);
1645 init = vds->var()->var_value()->init();
1647 return TRAVERSE_CONTINUE;
1648 init->traverse(&init, &find_shortcut);
1650 Expression** pshortcut = find_shortcut.found();
1651 if (pshortcut == NULL)
1652 return TRAVERSE_CONTINUE;
1654 Statement* snew = this->convert_shortcut(block, pshortcut);
1655 block->insert_statement_before(*pindex, snew);
1658 if (pshortcut == &init)
1659 vds->var()->var_value()->set_init(init);
1663 // Remove shortcut operators in the initializer of a global variable.
1666 Shortcuts::variable(Named_object* no)
1668 if (no->is_result_variable())
1669 return TRAVERSE_CONTINUE;
1670 Variable* var = no->var_value();
1671 Expression* init = var->init();
1672 if (!var->is_global() || init == NULL)
1673 return TRAVERSE_CONTINUE;
1677 Find_shortcut find_shortcut;
1678 init->traverse(&init, &find_shortcut);
1679 Expression** pshortcut = find_shortcut.found();
1680 if (pshortcut == NULL)
1681 return TRAVERSE_CONTINUE;
1683 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1684 var->add_preinit_statement(snew);
1685 if (pshortcut == &init)
1686 var->set_init(init);
1690 // Given an expression which uses a shortcut operator, return a
1691 // statement which implements it, and update *PSHORTCUT accordingly.
1694 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1696 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1697 Expression* left = shortcut->left();
1698 Expression* right = shortcut->right();
1699 source_location loc = shortcut->location();
1701 Block* retblock = new Block(enclosing, loc);
1702 retblock->set_end_location(loc);
1704 Temporary_statement* ts = Statement::make_temporary(Type::make_boolean_type(),
1706 retblock->add_statement(ts);
1708 Block* block = new Block(retblock, loc);
1709 block->set_end_location(loc);
1710 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1711 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1712 block->add_statement(assign);
1714 Expression* cond = Expression::make_temporary_reference(ts, loc);
1715 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1716 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1718 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1720 retblock->add_statement(if_statement);
1722 *pshortcut = Expression::make_temporary_reference(ts, loc);
1726 // Now convert any shortcut operators in LEFT and RIGHT.
1727 Shortcuts shortcuts;
1728 retblock->traverse(&shortcuts);
1730 return Statement::make_block_statement(retblock, loc);
1733 // Turn shortcut operators into explicit if statements. Doing this
1734 // considerably simplifies the order of evaluation rules.
1737 Gogo::remove_shortcuts()
1739 Shortcuts shortcuts;
1740 this->traverse(&shortcuts);
1743 // A traversal class which finds all the expressions which must be
1744 // evaluated in order within a statement or larger expression. This
1745 // is used to implement the rules about order of evaluation.
1747 class Find_eval_ordering : public Traverse
1750 typedef std::vector<Expression**> Expression_pointers;
1753 Find_eval_ordering()
1754 : Traverse(traverse_blocks
1755 | traverse_statements
1756 | traverse_expressions),
1762 { return this->exprs_.size(); }
1764 typedef Expression_pointers::const_iterator const_iterator;
1768 { return this->exprs_.begin(); }
1772 { return this->exprs_.end(); }
1777 { return TRAVERSE_SKIP_COMPONENTS; }
1780 statement(Block*, size_t*, Statement*)
1781 { return TRAVERSE_SKIP_COMPONENTS; }
1784 expression(Expression**);
1787 // A list of pointers to expressions with side-effects.
1788 Expression_pointers exprs_;
1791 // If an expression must be evaluated in order, put it on the list.
1794 Find_eval_ordering::expression(Expression** expression_pointer)
1796 // We have to look at subexpressions before this one.
1797 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1798 return TRAVERSE_EXIT;
1799 if ((*expression_pointer)->must_eval_in_order())
1800 this->exprs_.push_back(expression_pointer);
1801 return TRAVERSE_SKIP_COMPONENTS;
1804 // A traversal class for ordering evaluations.
1806 class Order_eval : public Traverse
1810 : Traverse(traverse_variables
1811 | traverse_statements)
1815 variable(Named_object*);
1818 statement(Block*, size_t*, Statement*);
1821 // Implement the order of evaluation rules for a statement.
1824 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1826 // FIXME: This approach doesn't work for switch statements, because
1827 // we add the new statements before the whole switch when we need to
1828 // instead add them just before the switch expression. The right
1829 // fix is probably to lower switch statements with nonconstant cases
1830 // to a series of conditionals.
1831 if (s->switch_statement() != NULL)
1832 return TRAVERSE_CONTINUE;
1834 Find_eval_ordering find_eval_ordering;
1836 // If S is a variable declaration, then ordinary traversal won't do
1837 // anything. We want to explicitly traverse the initialization
1838 // expression if there is one.
1839 Variable_declaration_statement* vds = s->variable_declaration_statement();
1840 Expression* init = NULL;
1841 Expression* orig_init = NULL;
1843 s->traverse_contents(&find_eval_ordering);
1846 init = vds->var()->var_value()->init();
1848 return TRAVERSE_CONTINUE;
1851 // It might seem that this could be
1852 // init->traverse_subexpressions. Unfortunately that can fail
1855 // newvar, err := call(arg())
1856 // Here newvar will have an init of call result 0 of
1857 // call(arg()). If we only traverse subexpressions, we will
1858 // only find arg(), and we won't bother to move anything out.
1859 // Then we get to the assignment to err, we will traverse the
1860 // whole statement, and this time we will find both call() and
1861 // arg(), and so we will move them out. This will cause them to
1862 // be put into temporary variables before the assignment to err
1863 // but after the declaration of newvar. To avoid that problem,
1864 // we traverse the entire expression here.
1865 Expression::traverse(&init, &find_eval_ordering);
1868 if (find_eval_ordering.size() <= 1)
1870 // If there is only one expression with a side-effect, we can
1871 // leave it in place.
1872 return TRAVERSE_CONTINUE;
1875 bool is_thunk = s->thunk_statement() != NULL;
1876 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1877 p != find_eval_ordering.end();
1880 Expression** pexpr = *p;
1882 // If the last expression is a send or receive expression, we
1883 // may be ignoring the value; we don't want to evaluate it
1885 if (p + 1 == find_eval_ordering.end()
1886 && ((*pexpr)->classification() == Expression::EXPRESSION_SEND
1887 || (*pexpr)->classification() == Expression::EXPRESSION_RECEIVE))
1890 // The last expression in a thunk will be the call passed to go
1891 // or defer, which we must not evaluate early.
1892 if (is_thunk && p + 1 == find_eval_ordering.end())
1895 source_location loc = (*pexpr)->location();
1896 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1897 block->insert_statement_before(*pindex, ts);
1900 *pexpr = Expression::make_temporary_reference(ts, loc);
1903 if (init != orig_init)
1904 vds->var()->var_value()->set_init(init);
1906 return TRAVERSE_CONTINUE;
1909 // Implement the order of evaluation rules for the initializer of a
1913 Order_eval::variable(Named_object* no)
1915 if (no->is_result_variable())
1916 return TRAVERSE_CONTINUE;
1917 Variable* var = no->var_value();
1918 Expression* init = var->init();
1919 if (!var->is_global() || init == NULL)
1920 return TRAVERSE_CONTINUE;
1922 Find_eval_ordering find_eval_ordering;
1923 init->traverse_subexpressions(&find_eval_ordering);
1925 if (find_eval_ordering.size() <= 1)
1927 // If there is only one expression with a side-effect, we can
1928 // leave it in place.
1929 return TRAVERSE_SKIP_COMPONENTS;
1932 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1933 p != find_eval_ordering.end();
1936 Expression** pexpr = *p;
1937 source_location loc = (*pexpr)->location();
1938 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1939 var->add_preinit_statement(ts);
1940 *pexpr = Expression::make_temporary_reference(ts, loc);
1943 return TRAVERSE_SKIP_COMPONENTS;
1946 // Use temporary variables to implement the order of evaluation rules.
1949 Gogo::order_evaluations()
1951 Order_eval order_eval;
1952 this->traverse(&order_eval);
1955 // Traversal to convert calls to the predeclared recover function to
1956 // pass in an argument indicating whether it can recover from a panic
1959 class Convert_recover : public Traverse
1962 Convert_recover(Named_object* arg)
1963 : Traverse(traverse_expressions),
1969 expression(Expression**);
1972 // The argument to pass to the function.
1976 // Convert calls to recover.
1979 Convert_recover::expression(Expression** pp)
1981 Call_expression* ce = (*pp)->call_expression();
1982 if (ce != NULL && ce->is_recover_call())
1983 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
1985 return TRAVERSE_CONTINUE;
1988 // Traversal for build_recover_thunks.
1990 class Build_recover_thunks : public Traverse
1993 Build_recover_thunks(Gogo* gogo)
1994 : Traverse(traverse_functions),
1999 function(Named_object*);
2003 can_recover_arg(source_location);
2009 // If this function calls recover, turn it into a thunk.
2012 Build_recover_thunks::function(Named_object* orig_no)
2014 Function* orig_func = orig_no->func_value();
2015 if (!orig_func->calls_recover()
2016 || orig_func->is_recover_thunk()
2017 || orig_func->has_recover_thunk())
2018 return TRAVERSE_CONTINUE;
2020 Gogo* gogo = this->gogo_;
2021 source_location location = orig_func->location();
2026 Function_type* orig_fntype = orig_func->type();
2027 Typed_identifier_list* new_params = new Typed_identifier_list();
2028 std::string receiver_name;
2029 if (orig_fntype->is_method())
2031 const Typed_identifier* receiver = orig_fntype->receiver();
2032 snprintf(buf, sizeof buf, "rt.%u", count);
2034 receiver_name = buf;
2035 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2036 receiver->location()));
2038 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2039 if (orig_params != NULL && !orig_params->empty())
2041 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2042 p != orig_params->end();
2045 snprintf(buf, sizeof buf, "pt.%u", count);
2047 new_params->push_back(Typed_identifier(buf, p->type(),
2051 snprintf(buf, sizeof buf, "pr.%u", count);
2053 std::string can_recover_name = buf;
2054 new_params->push_back(Typed_identifier(can_recover_name,
2055 Type::make_boolean_type(),
2056 orig_fntype->location()));
2058 const Typed_identifier_list* orig_results = orig_fntype->results();
2059 Typed_identifier_list* new_results;
2060 if (orig_results == NULL || orig_results->empty())
2064 new_results = new Typed_identifier_list();
2065 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2066 p != orig_results->end();
2068 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2071 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2073 orig_fntype->location());
2074 if (orig_fntype->is_varargs())
2075 new_fntype->set_is_varargs();
2077 std::string name = orig_no->name() + "$recover";
2078 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2080 Function *new_func = new_no->func_value();
2081 if (orig_func->enclosing() != NULL)
2082 new_func->set_enclosing(orig_func->enclosing());
2084 // We build the code for the original function attached to the new
2085 // function, and then swap the original and new function bodies.
2086 // This means that existing references to the original function will
2087 // then refer to the new function. That makes this code a little
2088 // confusing, in that the reference to NEW_NO really refers to the
2089 // other function, not the one we are building.
2091 Expression* closure = NULL;
2092 if (orig_func->needs_closure())
2094 Named_object* orig_closure_no = orig_func->closure_var();
2095 Variable* orig_closure_var = orig_closure_no->var_value();
2096 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2097 true, false, location);
2098 snprintf(buf, sizeof buf, "closure.%u", count);
2100 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2102 new_func->set_closure_var(new_closure_no);
2103 closure = Expression::make_var_reference(new_closure_no, location);
2106 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2108 Expression_list* args = new Expression_list();
2109 if (new_params != NULL)
2111 // Note that we skip the last parameter, which is the boolean
2112 // indicating whether recover can succed.
2113 for (Typed_identifier_list::const_iterator p = new_params->begin();
2114 p + 1 != new_params->end();
2117 Named_object* p_no = gogo->lookup(p->name(), NULL);
2118 gcc_assert(p_no != NULL
2119 && p_no->is_variable()
2120 && p_no->var_value()->is_parameter());
2121 args->push_back(Expression::make_var_reference(p_no, location));
2124 args->push_back(this->can_recover_arg(location));
2126 Call_expression* call = Expression::make_call(fn, args, false, location);
2129 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2130 s = Statement::make_statement(call);
2133 Expression_list* vals = new Expression_list();
2134 size_t rc = orig_fntype->results()->size();
2136 vals->push_back(call);
2139 for (size_t i = 0; i < rc; ++i)
2140 vals->push_back(Expression::make_call_result(call, i));
2142 s = Statement::make_return_statement(new_func->type()->results(),
2145 s->determine_types();
2146 gogo->add_statement(s);
2148 gogo->finish_function(location);
2150 // Swap the function bodies and types.
2151 new_func->swap_for_recover(orig_func);
2152 orig_func->set_is_recover_thunk();
2153 new_func->set_calls_recover();
2154 new_func->set_has_recover_thunk();
2156 Bindings* orig_bindings = orig_func->block()->bindings();
2157 Bindings* new_bindings = new_func->block()->bindings();
2158 if (orig_fntype->is_method())
2160 // We changed the receiver to be a regular parameter. We have
2161 // to update the binding accordingly in both functions.
2162 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2163 gcc_assert(orig_rec_no != NULL
2164 && orig_rec_no->is_variable()
2165 && !orig_rec_no->var_value()->is_receiver());
2166 orig_rec_no->var_value()->set_is_receiver();
2168 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2169 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2170 gcc_assert(new_rec_no != NULL
2171 && new_rec_no->is_variable()
2172 && new_rec_no->var_value()->is_receiver());
2173 new_rec_no->var_value()->set_is_not_receiver();
2176 // Because we flipped blocks but not types, the can_recover
2177 // parameter appears in the (now) old bindings as a parameter.
2178 // Change it to a local variable, whereupon it will be discarded.
2179 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2180 gcc_assert(can_recover_no != NULL
2181 && can_recover_no->is_variable()
2182 && can_recover_no->var_value()->is_parameter());
2183 orig_bindings->remove_binding(can_recover_no);
2185 // Add the can_recover argument to the (now) new bindings, and
2186 // attach it to any recover statements.
2187 Variable* can_recover_var = new Variable(Type::make_boolean_type(), NULL,
2188 false, true, false, location);
2189 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2191 Convert_recover convert_recover(can_recover_no);
2192 new_func->traverse(&convert_recover);
2194 // Update the function pointers in any named results.
2195 new_func->update_named_result_variables();
2196 orig_func->update_named_result_variables();
2198 return TRAVERSE_CONTINUE;
2201 // Return the expression to pass for the .can_recover parameter to the
2202 // new function. This indicates whether a call to recover may return
2203 // non-nil. The expression is
2204 // __go_can_recover(__builtin_return_address()).
2207 Build_recover_thunks::can_recover_arg(source_location location)
2209 static Named_object* builtin_return_address;
2210 if (builtin_return_address == NULL)
2212 const source_location bloc = BUILTINS_LOCATION;
2214 Typed_identifier_list* param_types = new Typed_identifier_list();
2215 Type* uint_type = Type::lookup_integer_type("uint");
2216 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2218 Typed_identifier_list* return_types = new Typed_identifier_list();
2219 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2220 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2222 Function_type* fntype = Type::make_function_type(NULL, param_types,
2223 return_types, bloc);
2224 builtin_return_address =
2225 Named_object::make_function_declaration("__builtin_return_address",
2226 NULL, fntype, bloc);
2227 const char* n = "__builtin_return_address";
2228 builtin_return_address->func_declaration_value()->set_asm_name(n);
2231 static Named_object* can_recover;
2232 if (can_recover == NULL)
2234 const source_location bloc = BUILTINS_LOCATION;
2235 Typed_identifier_list* param_types = new Typed_identifier_list();
2236 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2237 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2238 Type* boolean_type = Type::make_boolean_type();
2239 Typed_identifier_list* results = new Typed_identifier_list();
2240 results->push_back(Typed_identifier("", boolean_type, bloc));
2241 Function_type* fntype = Type::make_function_type(NULL, param_types,
2243 can_recover = Named_object::make_function_declaration("__go_can_recover",
2246 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2249 Expression* fn = Expression::make_func_reference(builtin_return_address,
2253 mpz_init_set_ui(zval, 0UL);
2254 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2256 Expression_list *args = new Expression_list();
2257 args->push_back(zexpr);
2259 Expression* call = Expression::make_call(fn, args, false, location);
2261 args = new Expression_list();
2262 args->push_back(call);
2264 fn = Expression::make_func_reference(can_recover, NULL, location);
2265 return Expression::make_call(fn, args, false, location);
2268 // Build thunks for functions which call recover. We build a new
2269 // function with an extra parameter, which is whether a call to
2270 // recover can succeed. We then move the body of this function to
2271 // that one. We then turn this function into a thunk which calls the
2272 // new one, passing the value of
2273 // __go_can_recover(__builtin_return_address()). The function will be
2274 // marked as not splitting the stack. This will cooperate with the
2275 // implementation of defer to make recover do the right thing.
2278 Gogo::build_recover_thunks()
2280 Build_recover_thunks build_recover_thunks(this);
2281 this->traverse(&build_recover_thunks);
2284 // Look for named types to see whether we need to create an interface
2287 class Build_method_tables : public Traverse
2290 Build_method_tables(Gogo* gogo,
2291 const std::vector<Interface_type*>& interfaces)
2292 : Traverse(traverse_types),
2293 gogo_(gogo), interfaces_(interfaces)
2302 // A list of locally defined interfaces which have hidden methods.
2303 const std::vector<Interface_type*>& interfaces_;
2306 // Build all required interface method tables for types. We need to
2307 // ensure that we have an interface method table for every interface
2308 // which has a hidden method, for every named type which implements
2309 // that interface. Normally we can just build interface method tables
2310 // as we need them. However, in some cases we can require an
2311 // interface method table for an interface defined in a different
2312 // package for a type defined in that package. If that interface and
2313 // type both use a hidden method, that is OK. However, we will not be
2314 // able to build that interface method table when we need it, because
2315 // the type's hidden method will be static. So we have to build it
2316 // here, and just refer it from other packages as needed.
2319 Gogo::build_interface_method_tables()
2321 std::vector<Interface_type*> hidden_interfaces;
2322 hidden_interfaces.reserve(this->interface_types_.size());
2323 for (std::vector<Interface_type*>::const_iterator pi =
2324 this->interface_types_.begin();
2325 pi != this->interface_types_.end();
2328 const Typed_identifier_list* methods = (*pi)->methods();
2329 if (methods == NULL)
2331 for (Typed_identifier_list::const_iterator pm = methods->begin();
2332 pm != methods->end();
2335 if (Gogo::is_hidden_name(pm->name()))
2337 hidden_interfaces.push_back(*pi);
2343 if (!hidden_interfaces.empty())
2345 // Now traverse the tree looking for all named types.
2346 Build_method_tables bmt(this, hidden_interfaces);
2347 this->traverse(&bmt);
2350 // We no longer need the list of interfaces.
2352 this->interface_types_.clear();
2355 // This is called for each type. For a named type, for each of the
2356 // interfaces with hidden methods that it implements, create the
2360 Build_method_tables::type(Type* type)
2362 Named_type* nt = type->named_type();
2365 for (std::vector<Interface_type*>::const_iterator p =
2366 this->interfaces_.begin();
2367 p != this->interfaces_.end();
2370 // We ask whether a pointer to the named type implements the
2371 // interface, because a pointer can implement more methods
2373 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2375 nt->interface_method_table(this->gogo_, *p, false);
2376 nt->interface_method_table(this->gogo_, *p, true);
2380 return TRAVERSE_CONTINUE;
2383 // Traversal class used to check for return statements.
2385 class Check_return_statements_traverse : public Traverse
2388 Check_return_statements_traverse()
2389 : Traverse(traverse_functions)
2393 function(Named_object*);
2396 // Check that a function has a return statement if it needs one.
2399 Check_return_statements_traverse::function(Named_object* no)
2401 Function* func = no->func_value();
2402 const Function_type* fntype = func->type();
2403 const Typed_identifier_list* results = fntype->results();
2405 // We only need a return statement if there is a return value.
2406 if (results == NULL || results->empty())
2407 return TRAVERSE_CONTINUE;
2409 if (func->block()->may_fall_through())
2410 error_at(func->location(), "control reaches end of non-void function");
2412 return TRAVERSE_CONTINUE;
2415 // Check return statements.
2418 Gogo::check_return_statements()
2420 Check_return_statements_traverse traverse;
2421 this->traverse(&traverse);
2424 // Get the unique prefix to use before all exported symbols. This
2425 // must be unique across the entire link.
2428 Gogo::unique_prefix() const
2430 gcc_assert(!this->unique_prefix_.empty());
2431 return this->unique_prefix_;
2434 // Set the unique prefix to use before all exported symbols. This
2435 // comes from the command line option -fgo-prefix=XXX.
2438 Gogo::set_unique_prefix(const std::string& arg)
2440 gcc_assert(this->unique_prefix_.empty());
2441 this->unique_prefix_ = arg;
2444 // Work out the package priority. It is one more than the maximum
2445 // priority of an imported package.
2448 Gogo::package_priority() const
2451 for (Packages::const_iterator p = this->packages_.begin();
2452 p != this->packages_.end();
2454 if (p->second->priority() > priority)
2455 priority = p->second->priority();
2456 return priority + 1;
2459 // Export identifiers as requested.
2464 // For now we always stream to a section. Later we may want to
2465 // support streaming to a separate file.
2466 Stream_to_section stream;
2468 Export exp(&stream);
2469 exp.register_builtin_types(this);
2470 exp.export_globals(this->package_name(),
2471 this->unique_prefix(),
2472 this->package_priority(),
2473 (this->need_init_fn_ && this->package_name() != "main"
2474 ? this->get_init_fn_name()
2476 this->imported_init_fns_,
2477 this->package_->bindings());
2482 Function::Function(Function_type* type, Function* enclosing, Block* block,
2483 source_location location)
2484 : type_(type), enclosing_(enclosing), named_results_(NULL),
2485 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2486 defer_stack_(NULL), calls_recover_(false), is_recover_thunk_(false),
2487 has_recover_thunk_(false)
2491 // Create the named result variables.
2494 Function::create_named_result_variables(Gogo* gogo)
2496 const Typed_identifier_list* results = this->type_->results();
2499 || results->front().name().empty())
2502 this->named_results_ = new Named_results();
2503 this->named_results_->reserve(results->size());
2505 Block* block = this->block_;
2507 for (Typed_identifier_list::const_iterator p = results->begin();
2508 p != results->end();
2511 std::string name = p->name();
2512 if (Gogo::is_sink_name(name))
2514 static int unnamed_result_counter;
2516 snprintf(buf, sizeof buf, "_$%d", unnamed_result_counter);
2517 ++unnamed_result_counter;
2518 name = gogo->pack_hidden_name(buf, false);
2520 Result_variable* result = new Result_variable(p->type(), this, index);
2521 Named_object* no = block->bindings()->add_result_variable(name, result);
2522 this->named_results_->push_back(no);
2526 // Update the named result variables when cloning a function which
2530 Function::update_named_result_variables()
2532 if (this->named_results_ == NULL)
2535 for (Named_results::iterator p = this->named_results_->begin();
2536 p != this->named_results_->end();
2538 (*p)->result_var_value()->set_function(this);
2541 // Return the closure variable, creating it if necessary.
2544 Function::closure_var()
2546 if (this->closure_var_ == NULL)
2548 // We don't know the type of the variable yet. We add fields as
2550 source_location loc = this->type_->location();
2551 Struct_field_list* sfl = new Struct_field_list;
2552 Type* struct_type = Type::make_struct_type(sfl, loc);
2553 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2554 NULL, false, true, false, loc);
2555 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2556 // Note that the new variable is not in any binding contour.
2558 return this->closure_var_;
2561 // Set the type of the closure variable.
2564 Function::set_closure_type()
2566 if (this->closure_var_ == NULL)
2568 Named_object* closure = this->closure_var_;
2569 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2570 unsigned int index = 0;
2571 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2572 p != this->closure_fields_.end();
2575 Named_object* no = p->first;
2577 snprintf(buf, sizeof buf, "%u", index);
2578 std::string n = no->name() + buf;
2580 if (no->is_variable())
2581 var_type = no->var_value()->type();
2583 var_type = no->result_var_value()->type();
2584 Type* field_type = Type::make_pointer_type(var_type);
2585 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2589 // Return whether this function is a method.
2592 Function::is_method() const
2594 return this->type_->is_method();
2597 // Add a label definition.
2600 Function::add_label_definition(const std::string& label_name,
2601 source_location location)
2603 Label* lnull = NULL;
2604 std::pair<Labels::iterator, bool> ins =
2605 this->labels_.insert(std::make_pair(label_name, lnull));
2608 // This is a new label.
2609 Label* label = new Label(label_name);
2610 label->define(location);
2611 ins.first->second = label;
2616 // The label was already in the hash table.
2617 Label* label = ins.first->second;
2618 if (!label->is_defined())
2620 label->define(location);
2625 error_at(location, "redefinition of label %qs",
2626 Gogo::message_name(label_name).c_str());
2627 inform(label->location(), "previous definition of %qs was here",
2628 Gogo::message_name(label_name).c_str());
2629 return new Label(label_name);
2634 // Add a reference to a label.
2637 Function::add_label_reference(const std::string& label_name)
2639 Label* lnull = NULL;
2640 std::pair<Labels::iterator, bool> ins =
2641 this->labels_.insert(std::make_pair(label_name, lnull));
2644 // The label was already in the hash table.
2645 return ins.first->second;
2649 gcc_assert(ins.first->second == NULL);
2650 Label* label = new Label(label_name);
2651 ins.first->second = label;
2656 // Swap one function with another. This is used when building the
2657 // thunk we use to call a function which calls recover. It may not
2658 // work for any other case.
2661 Function::swap_for_recover(Function *x)
2663 gcc_assert(this->enclosing_ == x->enclosing_);
2664 std::swap(this->named_results_, x->named_results_);
2665 std::swap(this->closure_var_, x->closure_var_);
2666 std::swap(this->block_, x->block_);
2667 gcc_assert(this->location_ == x->location_);
2668 gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2669 gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2672 // Traverse the tree.
2675 Function::traverse(Traverse* traverse)
2677 unsigned int traverse_mask = traverse->traverse_mask();
2680 & (Traverse::traverse_types | Traverse::traverse_expressions))
2683 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2684 return TRAVERSE_EXIT;
2687 // FIXME: We should check traverse_functions here if nested
2688 // functions are stored in block bindings.
2689 if (this->block_ != NULL
2691 & (Traverse::traverse_variables
2692 | Traverse::traverse_constants
2693 | Traverse::traverse_blocks
2694 | Traverse::traverse_statements
2695 | Traverse::traverse_expressions
2696 | Traverse::traverse_types)) != 0)
2698 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2699 return TRAVERSE_EXIT;
2702 return TRAVERSE_CONTINUE;
2705 // Work out types for unspecified variables and constants.
2708 Function::determine_types()
2710 if (this->block_ != NULL)
2711 this->block_->determine_types();
2714 // Export the function.
2717 Function::export_func(Export* exp, const std::string& name) const
2719 Function::export_func_with_type(exp, name, this->type_);
2722 // Export a function with a type.
2725 Function::export_func_with_type(Export* exp, const std::string& name,
2726 const Function_type* fntype)
2728 exp->write_c_string("func ");
2730 if (fntype->is_method())
2732 exp->write_c_string("(");
2733 exp->write_type(fntype->receiver()->type());
2734 exp->write_c_string(") ");
2737 exp->write_string(name);
2739 exp->write_c_string(" (");
2740 const Typed_identifier_list* parameters = fntype->parameters();
2741 if (parameters != NULL)
2743 bool is_varargs = fntype->is_varargs();
2745 for (Typed_identifier_list::const_iterator p = parameters->begin();
2746 p != parameters->end();
2752 exp->write_c_string(", ");
2753 if (!is_varargs || p + 1 != parameters->end())
2754 exp->write_type(p->type());
2757 exp->write_c_string("...");
2758 exp->write_type(p->type()->array_type()->element_type());
2762 exp->write_c_string(")");
2764 const Typed_identifier_list* results = fntype->results();
2765 if (results != NULL)
2767 if (results->size() == 1)
2769 exp->write_c_string(" ");
2770 exp->write_type(results->begin()->type());
2774 exp->write_c_string(" (");
2776 for (Typed_identifier_list::const_iterator p = results->begin();
2777 p != results->end();
2783 exp->write_c_string(", ");
2784 exp->write_type(p->type());
2786 exp->write_c_string(")");
2789 exp->write_c_string(";\n");
2792 // Import a function.
2795 Function::import_func(Import* imp, std::string* pname,
2796 Typed_identifier** preceiver,
2797 Typed_identifier_list** pparameters,
2798 Typed_identifier_list** presults,
2801 imp->require_c_string("func ");
2804 if (imp->peek_char() == '(')
2806 imp->require_c_string("(");
2807 Type* rtype = imp->read_type();
2808 *preceiver = new Typed_identifier(Import::import_marker, rtype,
2810 imp->require_c_string(") ");
2813 *pname = imp->read_identifier();
2815 Typed_identifier_list* parameters;
2816 *is_varargs = false;
2817 imp->require_c_string(" (");
2818 if (imp->peek_char() == ')')
2822 parameters = new Typed_identifier_list();
2825 if (imp->match_c_string("..."))
2831 Type* ptype = imp->read_type();
2833 ptype = Type::make_array_type(ptype, NULL);
2834 parameters->push_back(Typed_identifier(Import::import_marker,
2835 ptype, imp->location()));
2836 if (imp->peek_char() != ',')
2838 gcc_assert(!*is_varargs);
2839 imp->require_c_string(", ");
2842 imp->require_c_string(")");
2843 *pparameters = parameters;
2845 Typed_identifier_list* results;
2846 if (imp->peek_char() != ' ')
2850 results = new Typed_identifier_list();
2851 imp->require_c_string(" ");
2852 if (imp->peek_char() != '(')
2854 Type* rtype = imp->read_type();
2855 results->push_back(Typed_identifier(Import::import_marker, rtype,
2860 imp->require_c_string("(");
2863 Type* rtype = imp->read_type();
2864 results->push_back(Typed_identifier(Import::import_marker,
2865 rtype, imp->location()));
2866 if (imp->peek_char() != ',')
2868 imp->require_c_string(", ");
2870 imp->require_c_string(")");
2873 imp->require_c_string(";\n");
2874 *presults = results;
2879 Block::Block(Block* enclosing, source_location location)
2880 : enclosing_(enclosing), statements_(),
2881 bindings_(new Bindings(enclosing == NULL
2883 : enclosing->bindings())),
2884 start_location_(location),
2885 end_location_(UNKNOWN_LOCATION)
2889 // Add a statement to a block.
2892 Block::add_statement(Statement* statement)
2894 this->statements_.push_back(statement);
2897 // Add a statement to the front of a block. This is slow but is only
2898 // used for reference counts of parameters.
2901 Block::add_statement_at_front(Statement* statement)
2903 this->statements_.insert(this->statements_.begin(), statement);
2906 // Replace a statement in a block.
2909 Block::replace_statement(size_t index, Statement* s)
2911 gcc_assert(index < this->statements_.size());
2912 this->statements_[index] = s;
2915 // Add a statement before another statement.
2918 Block::insert_statement_before(size_t index, Statement* s)
2920 gcc_assert(index < this->statements_.size());
2921 this->statements_.insert(this->statements_.begin() + index, s);
2924 // Add a statement after another statement.
2927 Block::insert_statement_after(size_t index, Statement* s)
2929 gcc_assert(index < this->statements_.size());
2930 this->statements_.insert(this->statements_.begin() + index + 1, s);
2933 // Traverse the tree.
2936 Block::traverse(Traverse* traverse)
2938 unsigned int traverse_mask = traverse->traverse_mask();
2940 if ((traverse_mask & Traverse::traverse_blocks) != 0)
2942 int t = traverse->block(this);
2943 if (t == TRAVERSE_EXIT)
2944 return TRAVERSE_EXIT;
2945 else if (t == TRAVERSE_SKIP_COMPONENTS)
2946 return TRAVERSE_CONTINUE;
2950 & (Traverse::traverse_variables
2951 | Traverse::traverse_constants
2952 | Traverse::traverse_expressions
2953 | Traverse::traverse_types)) != 0)
2955 for (Bindings::const_definitions_iterator pb =
2956 this->bindings_->begin_definitions();
2957 pb != this->bindings_->end_definitions();
2960 switch ((*pb)->classification())
2962 case Named_object::NAMED_OBJECT_CONST:
2963 if ((traverse_mask & Traverse::traverse_constants) != 0)
2965 if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
2966 return TRAVERSE_EXIT;
2968 if ((traverse_mask & Traverse::traverse_types) != 0
2969 || (traverse_mask & Traverse::traverse_expressions) != 0)
2971 Type* t = (*pb)->const_value()->type();
2973 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
2974 return TRAVERSE_EXIT;
2976 if ((traverse_mask & Traverse::traverse_expressions) != 0
2977 || (traverse_mask & Traverse::traverse_types) != 0)
2979 if ((*pb)->const_value()->traverse_expression(traverse)
2981 return TRAVERSE_EXIT;
2985 case Named_object::NAMED_OBJECT_VAR:
2986 case Named_object::NAMED_OBJECT_RESULT_VAR:
2987 if ((traverse_mask & Traverse::traverse_variables) != 0)
2989 if (traverse->variable(*pb) == TRAVERSE_EXIT)
2990 return TRAVERSE_EXIT;
2992 if (((traverse_mask & Traverse::traverse_types) != 0
2993 || (traverse_mask & Traverse::traverse_expressions) != 0)
2994 && ((*pb)->is_result_variable()
2995 || (*pb)->var_value()->has_type()))
2997 Type* t = ((*pb)->is_variable()
2998 ? (*pb)->var_value()->type()
2999 : (*pb)->result_var_value()->type());
3001 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3002 return TRAVERSE_EXIT;
3004 if ((*pb)->is_variable()
3005 && ((traverse_mask & Traverse::traverse_expressions) != 0
3006 || (traverse_mask & Traverse::traverse_types) != 0))
3008 if ((*pb)->var_value()->traverse_expression(traverse)
3010 return TRAVERSE_EXIT;
3014 case Named_object::NAMED_OBJECT_FUNC:
3015 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3016 // FIXME: Where will nested functions be found?
3019 case Named_object::NAMED_OBJECT_TYPE:
3020 if ((traverse_mask & Traverse::traverse_types) != 0
3021 || (traverse_mask & Traverse::traverse_expressions) != 0)
3023 if (Type::traverse((*pb)->type_value(), traverse)
3025 return TRAVERSE_EXIT;
3029 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3030 case Named_object::NAMED_OBJECT_UNKNOWN:
3033 case Named_object::NAMED_OBJECT_PACKAGE:
3034 case Named_object::NAMED_OBJECT_SINK:
3043 // No point in checking traverse_mask here--if we got here we always
3044 // want to walk the statements. The traversal can insert new
3045 // statements before or after the current statement. Inserting
3046 // statements before the current statement requires updating I via
3047 // the pointer; those statements will not be traversed. Any new
3048 // statements inserted after the current statement will be traversed
3050 for (size_t i = 0; i < this->statements_.size(); ++i)
3052 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3053 return TRAVERSE_EXIT;
3056 return TRAVERSE_CONTINUE;
3059 // Work out types for unspecified variables and constants.
3062 Block::determine_types()
3064 for (Bindings::const_definitions_iterator pb =
3065 this->bindings_->begin_definitions();
3066 pb != this->bindings_->end_definitions();
3069 if ((*pb)->is_variable())
3070 (*pb)->var_value()->determine_type();
3071 else if ((*pb)->is_const())
3072 (*pb)->const_value()->determine_type();
3075 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3076 ps != this->statements_.end();
3078 (*ps)->determine_types();
3081 // Return true if the statements in this block may fall through.
3084 Block::may_fall_through() const
3086 if (this->statements_.empty())
3088 return this->statements_.back()->may_fall_through();
3093 Variable::Variable(Type* type, Expression* init, bool is_global,
3094 bool is_parameter, bool is_receiver,
3095 source_location location)
3096 : type_(type), init_(init), preinit_(NULL), location_(location),
3097 is_global_(is_global), is_parameter_(is_parameter),
3098 is_receiver_(is_receiver), is_varargs_parameter_(false),
3099 is_address_taken_(false), seen_(false), init_is_lowered_(false),
3100 type_from_init_tuple_(false), type_from_range_index_(false),
3101 type_from_range_value_(false), type_from_chan_element_(false),
3102 is_type_switch_var_(false)
3104 gcc_assert(type != NULL || init != NULL);
3105 gcc_assert(!is_parameter || init == NULL);
3108 // Traverse the initializer expression.
3111 Variable::traverse_expression(Traverse* traverse)
3113 if (this->preinit_ != NULL)
3115 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3116 return TRAVERSE_EXIT;
3118 if (this->init_ != NULL)
3120 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3121 return TRAVERSE_EXIT;
3123 return TRAVERSE_CONTINUE;
3126 // Lower the initialization expression after parsing is complete.
3129 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3131 if (this->init_ != NULL && !this->init_is_lowered_)
3135 // We will give an error elsewhere, this is just to prevent
3136 // an infinite loop.
3141 gogo->lower_expression(function, &this->init_);
3143 this->seen_ = false;
3145 this->init_is_lowered_ = true;
3149 // Get the preinit block.
3152 Variable::preinit_block()
3154 gcc_assert(this->is_global_);
3155 if (this->preinit_ == NULL)
3156 this->preinit_ = new Block(NULL, this->location());
3157 return this->preinit_;
3160 // Add a statement to be run before the initialization expression.
3163 Variable::add_preinit_statement(Statement* s)
3165 Block* b = this->preinit_block();
3166 b->add_statement(s);
3167 b->set_end_location(s->location());
3170 // In an assignment which sets a variable to a tuple of EXPR, return
3171 // the type of the first element of the tuple.
3174 Variable::type_from_tuple(Expression* expr, bool report_error) const
3176 if (expr->map_index_expression() != NULL)
3178 Map_type* mt = expr->map_index_expression()->get_map_type();
3180 return Type::make_error_type();
3181 return mt->val_type();
3183 else if (expr->receive_expression() != NULL)
3185 Expression* channel = expr->receive_expression()->channel();
3186 Type* channel_type = channel->type();
3187 if (channel_type->channel_type() == NULL)
3188 return Type::make_error_type();
3189 return channel_type->channel_type()->element_type();
3194 error_at(this->location(), "invalid tuple definition");
3195 return Type::make_error_type();
3199 // Given EXPR used in a range clause, return either the index type or
3200 // the value type of the range, depending upon GET_INDEX_TYPE.
3203 Variable::type_from_range(Expression* expr, bool get_index_type,
3204 bool report_error) const
3206 Type* t = expr->type();
3207 if (t->array_type() != NULL
3208 || (t->points_to() != NULL
3209 && t->points_to()->array_type() != NULL
3210 && !t->points_to()->is_open_array_type()))
3213 return Type::lookup_integer_type("int");
3215 return t->deref()->array_type()->element_type();
3217 else if (t->is_string_type())
3218 return Type::lookup_integer_type("int");
3219 else if (t->map_type() != NULL)
3222 return t->map_type()->key_type();
3224 return t->map_type()->val_type();
3226 else if (t->channel_type() != NULL)
3229 return t->channel_type()->element_type();
3233 error_at(this->location(),
3234 "invalid definition of value variable for channel range");
3235 return Type::make_error_type();
3241 error_at(this->location(), "invalid type for range clause");
3242 return Type::make_error_type();
3246 // EXPR should be a channel. Return the channel's element type.
3249 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3251 Type* t = expr->type();
3252 if (t->channel_type() != NULL)
3253 return t->channel_type()->element_type();
3257 error_at(this->location(), "expected channel");
3258 return Type::make_error_type();
3262 // Return the type of the Variable. This may be called before
3263 // Variable::determine_type is called, which means that we may need to
3264 // get the type from the initializer. FIXME: If we combine lowering
3265 // with type determination, then this should be unnecessary.
3270 // A variable in a type switch with a nil case will have the wrong
3271 // type here. This gets fixed up in determine_type, below.
3272 Type* type = this->type_;
3273 Expression* init = this->init_;
3274 if (this->is_type_switch_var_
3275 && this->type_->is_nil_constant_as_type())
3277 Type_guard_expression* tge = this->init_->type_guard_expression();
3278 gcc_assert(tge != NULL);
3285 if (this->type_ == NULL || !this->type_->is_error_type())
3287 error_at(this->location_, "variable initializer refers to itself");
3288 this->type_ = Type::make_error_type();
3297 else if (this->type_from_init_tuple_)
3298 type = this->type_from_tuple(init, false);
3299 else if (this->type_from_range_index_ || this->type_from_range_value_)
3300 type = this->type_from_range(init, this->type_from_range_index_, false);
3301 else if (this->type_from_chan_element_)
3302 type = this->type_from_chan_element(init, false);
3305 gcc_assert(init != NULL);
3306 type = init->type();
3307 gcc_assert(type != NULL);
3309 // Variables should not have abstract types.
3310 if (type->is_abstract())
3311 type = type->make_non_abstract_type();
3313 if (type->is_void_type())
3314 type = Type::make_error_type();
3317 this->seen_ = false;
3322 // Fetch the type from a const pointer, in which case it should have
3323 // been set already.
3326 Variable::type() const
3328 gcc_assert(this->type_ != NULL);
3332 // Set the type if necessary.
3335 Variable::determine_type()
3337 // A variable in a type switch with a nil case will have the wrong
3338 // type here. It will have an initializer which is a type guard.
3339 // We want to initialize it to the value without the type guard, and
3340 // use the type of that value as well.
3341 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3343 Type_guard_expression* tge = this->init_->type_guard_expression();
3344 gcc_assert(tge != NULL);
3346 this->init_ = tge->expr();
3349 if (this->init_ == NULL)
3350 gcc_assert(this->type_ != NULL && !this->type_->is_abstract());
3351 else if (this->type_from_init_tuple_)
3353 Expression *init = this->init_;
3354 init->determine_type_no_context();
3355 this->type_ = this->type_from_tuple(init, true);
3358 else if (this->type_from_range_index_ || this->type_from_range_value_)
3360 Expression* init = this->init_;
3361 init->determine_type_no_context();
3362 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3368 // type_from_chan_element_ should have been cleared during
3370 gcc_assert(!this->type_from_chan_element_);
3372 Type_context context(this->type_, false);
3373 this->init_->determine_type(&context);
3374 if (this->type_ == NULL)
3376 Type* type = this->init_->type();
3377 gcc_assert(type != NULL);
3378 if (type->is_abstract())
3379 type = type->make_non_abstract_type();
3381 if (type->is_void_type())
3383 error_at(this->location_, "variable has no type");
3384 type = Type::make_error_type();
3386 else if (type->is_nil_type())
3388 error_at(this->location_, "variable defined to nil type");
3389 type = Type::make_error_type();
3391 else if (type->is_call_multiple_result_type())
3393 error_at(this->location_,
3394 "single variable set to multiple value function call");
3395 type = Type::make_error_type();
3403 // Export the variable
3406 Variable::export_var(Export* exp, const std::string& name) const
3408 gcc_assert(this->is_global_);
3409 exp->write_c_string("var ");
3410 exp->write_string(name);
3411 exp->write_c_string(" ");
3412 exp->write_type(this->type());
3413 exp->write_c_string(";\n");
3416 // Import a variable.
3419 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3421 imp->require_c_string("var ");
3422 *pname = imp->read_identifier();
3423 imp->require_c_string(" ");
3424 *ptype = imp->read_type();
3425 imp->require_c_string(";\n");
3428 // Class Named_constant.
3430 // Traverse the initializer expression.
3433 Named_constant::traverse_expression(Traverse* traverse)
3435 return Expression::traverse(&this->expr_, traverse);
3438 // Determine the type of the constant.
3441 Named_constant::determine_type()
3443 if (this->type_ != NULL)
3445 Type_context context(this->type_, false);
3446 this->expr_->determine_type(&context);
3450 // A constant may have an abstract type.
3451 Type_context context(NULL, true);
3452 this->expr_->determine_type(&context);
3453 this->type_ = this->expr_->type();
3454 gcc_assert(this->type_ != NULL);
3458 // Indicate that we found and reported an error for this constant.
3461 Named_constant::set_error()
3463 this->type_ = Type::make_error_type();
3464 this->expr_ = Expression::make_error(this->location_);
3467 // Export a constant.
3470 Named_constant::export_const(Export* exp, const std::string& name) const
3472 exp->write_c_string("const ");
3473 exp->write_string(name);
3474 exp->write_c_string(" ");
3475 if (!this->type_->is_abstract())
3477 exp->write_type(this->type_);
3478 exp->write_c_string(" ");
3480 exp->write_c_string("= ");
3481 this->expr()->export_expression(exp);
3482 exp->write_c_string(";\n");
3485 // Import a constant.
3488 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3491 imp->require_c_string("const ");
3492 *pname = imp->read_identifier();
3493 imp->require_c_string(" ");
3494 if (imp->peek_char() == '=')
3498 *ptype = imp->read_type();
3499 imp->require_c_string(" ");
3501 imp->require_c_string("= ");
3502 *pexpr = Expression::import_expression(imp);
3503 imp->require_c_string(";\n");
3509 Type_declaration::add_method(const std::string& name, Function* function)
3511 Named_object* ret = Named_object::make_function(name, NULL, function);
3512 this->methods_.push_back(ret);
3516 // Add a method declaration.
3519 Type_declaration::add_method_declaration(const std::string& name,
3520 Function_type* type,
3521 source_location location)
3523 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3525 this->methods_.push_back(ret);
3529 // Return whether any methods ere defined.
3532 Type_declaration::has_methods() const
3534 return !this->methods_.empty();
3537 // Define methods for the real type.
3540 Type_declaration::define_methods(Named_type* nt)
3542 for (Methods::const_iterator p = this->methods_.begin();
3543 p != this->methods_.end();
3545 nt->add_existing_method(*p);
3548 // We are using the type. Return true if we should issue a warning.
3551 Type_declaration::using_type()
3553 bool ret = !this->issued_warning_;
3554 this->issued_warning_ = true;
3558 // Class Unknown_name.
3560 // Set the real named object.
3563 Unknown_name::set_real_named_object(Named_object* no)
3565 gcc_assert(this->real_named_object_ == NULL);
3566 gcc_assert(!no->is_unknown());
3567 this->real_named_object_ = no;
3570 // Class Named_object.
3572 Named_object::Named_object(const std::string& name,
3573 const Package* package,
3574 Classification classification)
3575 : name_(name), package_(package), classification_(classification),
3578 if (Gogo::is_sink_name(name))
3579 gcc_assert(classification == NAMED_OBJECT_SINK);
3582 // Make an unknown name. This is used by the parser. The name must
3583 // be resolved later. Unknown names are only added in the current
3587 Named_object::make_unknown_name(const std::string& name,
3588 source_location location)
3590 Named_object* named_object = new Named_object(name, NULL,
3591 NAMED_OBJECT_UNKNOWN);
3592 Unknown_name* value = new Unknown_name(location);
3593 named_object->u_.unknown_value = value;
3594 return named_object;
3600 Named_object::make_constant(const Typed_identifier& tid,
3601 const Package* package, Expression* expr,
3604 Named_object* named_object = new Named_object(tid.name(), package,
3605 NAMED_OBJECT_CONST);
3606 Named_constant* named_constant = new Named_constant(tid.type(), expr,
3609 named_object->u_.const_value = named_constant;
3610 return named_object;
3613 // Make a named type.
3616 Named_object::make_type(const std::string& name, const Package* package,
3617 Type* type, source_location location)
3619 Named_object* named_object = new Named_object(name, package,
3621 Named_type* named_type = Type::make_named_type(named_object, type, location);
3622 named_object->u_.type_value = named_type;
3623 return named_object;
3626 // Make a type declaration.
3629 Named_object::make_type_declaration(const std::string& name,
3630 const Package* package,
3631 source_location location)
3633 Named_object* named_object = new Named_object(name, package,
3634 NAMED_OBJECT_TYPE_DECLARATION);
3635 Type_declaration* type_declaration = new Type_declaration(location);
3636 named_object->u_.type_declaration = type_declaration;
3637 return named_object;
3643 Named_object::make_variable(const std::string& name, const Package* package,
3646 Named_object* named_object = new Named_object(name, package,
3648 named_object->u_.var_value = variable;
3649 return named_object;
3652 // Make a result variable.
3655 Named_object::make_result_variable(const std::string& name,
3656 Result_variable* result)
3658 Named_object* named_object = new Named_object(name, NULL,
3659 NAMED_OBJECT_RESULT_VAR);
3660 named_object->u_.result_var_value = result;
3661 return named_object;
3664 // Make a sink. This is used for the special blank identifier _.
3667 Named_object::make_sink()
3669 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
3672 // Make a named function.
3675 Named_object::make_function(const std::string& name, const Package* package,
3678 Named_object* named_object = new Named_object(name, package,
3680 named_object->u_.func_value = function;
3681 return named_object;
3684 // Make a function declaration.
3687 Named_object::make_function_declaration(const std::string& name,
3688 const Package* package,
3689 Function_type* fntype,
3690 source_location location)
3692 Named_object* named_object = new Named_object(name, package,
3693 NAMED_OBJECT_FUNC_DECLARATION);
3694 Function_declaration *func_decl = new Function_declaration(fntype, location);
3695 named_object->u_.func_declaration_value = func_decl;
3696 return named_object;
3702 Named_object::make_package(const std::string& alias, Package* package)
3704 Named_object* named_object = new Named_object(alias, NULL,
3705 NAMED_OBJECT_PACKAGE);
3706 named_object->u_.package_value = package;
3707 return named_object;
3710 // Return the name to use in an error message.
3713 Named_object::message_name() const
3715 if (this->package_ == NULL)
3716 return Gogo::message_name(this->name_);
3717 std::string ret = Gogo::message_name(this->package_->name());
3719 ret += Gogo::message_name(this->name_);
3723 // Set the type when a declaration is defined.
3726 Named_object::set_type_value(Named_type* named_type)
3728 gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
3729 Type_declaration* td = this->u_.type_declaration;
3730 td->define_methods(named_type);
3731 Named_object* in_function = td->in_function();
3732 if (in_function != NULL)
3733 named_type->set_in_function(in_function);
3735 this->classification_ = NAMED_OBJECT_TYPE;
3736 this->u_.type_value = named_type;
3739 // Define a function which was previously declared.
3742 Named_object::set_function_value(Function* function)
3744 gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
3745 this->classification_ = NAMED_OBJECT_FUNC;
3746 // FIXME: We should free the old value.
3747 this->u_.func_value = function;
3750 // Declare an unknown object as a type declaration.
3753 Named_object::declare_as_type()
3755 gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
3756 Unknown_name* unk = this->u_.unknown_value;
3757 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
3758 this->u_.type_declaration = new Type_declaration(unk->location());
3762 // Return the location of a named object.
3765 Named_object::location() const
3767 switch (this->classification_)
3770 case NAMED_OBJECT_UNINITIALIZED:
3773 case NAMED_OBJECT_UNKNOWN:
3774 return this->unknown_value()->location();
3776 case NAMED_OBJECT_CONST:
3777 return this->const_value()->location();
3779 case NAMED_OBJECT_TYPE:
3780 return this->type_value()->location();
3782 case NAMED_OBJECT_TYPE_DECLARATION:
3783 return this->type_declaration_value()->location();
3785 case NAMED_OBJECT_VAR:
3786 return this->var_value()->location();
3788 case NAMED_OBJECT_RESULT_VAR:
3789 return this->result_var_value()->function()->location();
3791 case NAMED_OBJECT_SINK:
3794 case NAMED_OBJECT_FUNC:
3795 return this->func_value()->location();
3797 case NAMED_OBJECT_FUNC_DECLARATION:
3798 return this->func_declaration_value()->location();
3800 case NAMED_OBJECT_PACKAGE:
3801 return this->package_value()->location();
3805 // Export a named object.
3808 Named_object::export_named_object(Export* exp) const
3810 switch (this->classification_)
3813 case NAMED_OBJECT_UNINITIALIZED:
3814 case NAMED_OBJECT_UNKNOWN:
3817 case NAMED_OBJECT_CONST:
3818 this->const_value()->export_const(exp, this->name_);
3821 case NAMED_OBJECT_TYPE:
3822 this->type_value()->export_named_type(exp, this->name_);
3825 case NAMED_OBJECT_TYPE_DECLARATION:
3826 error_at(this->type_declaration_value()->location(),
3827 "attempt to export %<%s%> which was declared but not defined",
3828 this->message_name().c_str());
3831 case NAMED_OBJECT_FUNC_DECLARATION:
3832 this->func_declaration_value()->export_func(exp, this->name_);
3835 case NAMED_OBJECT_VAR:
3836 this->var_value()->export_var(exp, this->name_);
3839 case NAMED_OBJECT_RESULT_VAR:
3840 case NAMED_OBJECT_SINK:
3843 case NAMED_OBJECT_FUNC:
3844 this->func_value()->export_func(exp, this->name_);
3851 Bindings::Bindings(Bindings* enclosing)
3852 : enclosing_(enclosing), named_objects_(), bindings_()
3859 Bindings::clear_file_scope()
3861 Contour::iterator p = this->bindings_.begin();
3862 while (p != this->bindings_.end())
3865 if (p->second->package() != NULL)
3867 else if (p->second->is_package())
3869 else if (p->second->is_function()
3870 && !p->second->func_value()->type()->is_method()
3871 && Gogo::unpack_hidden_name(p->second->name()) == "init")
3879 p = this->bindings_.erase(p);
3883 // Look up a symbol.
3886 Bindings::lookup(const std::string& name) const
3888 Contour::const_iterator p = this->bindings_.find(name);
3889 if (p != this->bindings_.end())
3890 return p->second->resolve();
3891 else if (this->enclosing_ != NULL)
3892 return this->enclosing_->lookup(name);
3897 // Look up a symbol locally.
3900 Bindings::lookup_local(const std::string& name) const
3902 Contour::const_iterator p = this->bindings_.find(name);
3903 if (p == this->bindings_.end())
3908 // Remove an object from a set of bindings. This is used for a
3909 // special case in thunks for functions which call recover.
3912 Bindings::remove_binding(Named_object* no)
3914 Contour::iterator pb = this->bindings_.find(no->name());
3915 gcc_assert(pb != this->bindings_.end());
3916 this->bindings_.erase(pb);
3917 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
3918 pn != this->named_objects_.end();
3923 this->named_objects_.erase(pn);
3930 // Add a method to the list of objects. This is not added to the
3931 // lookup table. This is so that we have a single list of objects
3932 // declared at the top level, which we walk through when it's time to
3933 // convert to trees.
3936 Bindings::add_method(Named_object* method)
3938 this->named_objects_.push_back(method);
3941 // Add a generic Named_object to a Contour.
3944 Bindings::add_named_object_to_contour(Contour* contour,
3945 Named_object* named_object)
3947 gcc_assert(named_object == named_object->resolve());
3948 const std::string& name(named_object->name());
3949 gcc_assert(!Gogo::is_sink_name(name));
3951 std::pair<Contour::iterator, bool> ins =
3952 contour->insert(std::make_pair(name, named_object));
3955 // The name was already there.
3956 if (named_object->package() != NULL
3957 && ins.first->second->package() == named_object->package()
3958 && (ins.first->second->classification()
3959 == named_object->classification()))
3961 // This is a second import of the same object.
3962 return ins.first->second;
3964 ins.first->second = this->new_definition(ins.first->second,
3966 return ins.first->second;
3970 // Don't push declarations on the list. We push them on when
3971 // and if we find the definitions. That way we genericize the
3972 // functions in order.
3973 if (!named_object->is_type_declaration()
3974 && !named_object->is_function_declaration()
3975 && !named_object->is_unknown())
3976 this->named_objects_.push_back(named_object);
3977 return named_object;
3981 // We had an existing named object OLD_OBJECT, and we've seen a new
3982 // one NEW_OBJECT with the same name. FIXME: This does not free the
3983 // new object when we don't need it.
3986 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
3989 switch (old_object->classification())
3992 case Named_object::NAMED_OBJECT_UNINITIALIZED:
3995 case Named_object::NAMED_OBJECT_UNKNOWN:
3997 Named_object* real = old_object->unknown_value()->real_named_object();
3999 return this->new_definition(real, new_object);
4000 gcc_assert(!new_object->is_unknown());
4001 old_object->unknown_value()->set_real_named_object(new_object);
4002 if (!new_object->is_type_declaration()
4003 && !new_object->is_function_declaration())
4004 this->named_objects_.push_back(new_object);
4008 case Named_object::NAMED_OBJECT_CONST:
4011 case Named_object::NAMED_OBJECT_TYPE:
4012 if (new_object->is_type_declaration())
4016 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4017 if (new_object->is_type_declaration())
4019 if (new_object->is_type())
4021 old_object->set_type_value(new_object->type_value());
4022 new_object->type_value()->set_named_object(old_object);
4023 this->named_objects_.push_back(old_object);
4028 case Named_object::NAMED_OBJECT_VAR:
4029 case Named_object::NAMED_OBJECT_RESULT_VAR:
4032 case Named_object::NAMED_OBJECT_SINK:
4035 case Named_object::NAMED_OBJECT_FUNC:
4036 if (new_object->is_function_declaration())
4038 if (!new_object->func_declaration_value()->asm_name().empty())
4039 sorry("__asm__ for function definitions");
4040 Function_type* old_type = old_object->func_value()->type();
4041 Function_type* new_type =
4042 new_object->func_declaration_value()->type();
4043 if (old_type->is_valid_redeclaration(new_type, &reason))
4048 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4050 Function_type* old_type = old_object->func_declaration_value()->type();
4051 if (new_object->is_function_declaration())
4053 Function_type* new_type =
4054 new_object->func_declaration_value()->type();
4055 if (old_type->is_valid_redeclaration(new_type, &reason))
4058 if (new_object->is_function())
4060 Function_type* new_type = new_object->func_value()->type();
4061 if (old_type->is_valid_redeclaration(new_type, &reason))
4063 if (!old_object->func_declaration_value()->asm_name().empty())
4064 sorry("__asm__ for function definitions");
4065 old_object->set_function_value(new_object->func_value());
4066 this->named_objects_.push_back(old_object);
4073 case Named_object::NAMED_OBJECT_PACKAGE:
4074 if (new_object->is_package()
4075 && (old_object->package_value()->name()
4076 == new_object->package_value()->name()))
4082 std::string n = old_object->message_name();
4084 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4086 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4089 inform(old_object->location(), "previous definition of %qs was here",
4095 // Add a named type.
4098 Bindings::add_named_type(Named_type* named_type)
4100 return this->add_named_object(named_type->named_object());
4106 Bindings::add_function(const std::string& name, const Package* package,
4109 return this->add_named_object(Named_object::make_function(name, package,
4113 // Add a function declaration.
4116 Bindings::add_function_declaration(const std::string& name,
4117 const Package* package,
4118 Function_type* type,
4119 source_location location)
4121 Named_object* no = Named_object::make_function_declaration(name, package,
4123 return this->add_named_object(no);
4126 // Define a type which was previously declared.
4129 Bindings::define_type(Named_object* no, Named_type* type)
4131 no->set_type_value(type);
4132 this->named_objects_.push_back(no);
4135 // Traverse bindings.
4138 Bindings::traverse(Traverse* traverse, bool is_global)
4140 unsigned int traverse_mask = traverse->traverse_mask();
4142 // We don't use an iterator because we permit the traversal to add
4143 // new global objects.
4144 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4146 Named_object* p = this->named_objects_[i];
4147 switch (p->classification())
4149 case Named_object::NAMED_OBJECT_CONST:
4150 if ((traverse_mask & Traverse::traverse_constants) != 0)
4152 if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4153 return TRAVERSE_EXIT;
4155 if ((traverse_mask & Traverse::traverse_types) != 0
4156 || (traverse_mask & Traverse::traverse_expressions) != 0)
4158 Type* t = p->const_value()->type();
4160 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4161 return TRAVERSE_EXIT;
4162 if (p->const_value()->traverse_expression(traverse)
4164 return TRAVERSE_EXIT;
4168 case Named_object::NAMED_OBJECT_VAR:
4169 case Named_object::NAMED_OBJECT_RESULT_VAR:
4170 if ((traverse_mask & Traverse::traverse_variables) != 0)
4172 if (traverse->variable(p) == TRAVERSE_EXIT)
4173 return TRAVERSE_EXIT;
4175 if (((traverse_mask & Traverse::traverse_types) != 0
4176 || (traverse_mask & Traverse::traverse_expressions) != 0)
4177 && (p->is_result_variable()
4178 || p->var_value()->has_type()))
4180 Type* t = (p->is_variable()
4181 ? p->var_value()->type()
4182 : p->result_var_value()->type());
4184 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4185 return TRAVERSE_EXIT;
4187 if (p->is_variable()
4188 && ((traverse_mask & Traverse::traverse_types) != 0
4189 || (traverse_mask & Traverse::traverse_expressions) != 0))
4191 if (p->var_value()->traverse_expression(traverse)
4193 return TRAVERSE_EXIT;
4197 case Named_object::NAMED_OBJECT_FUNC:
4198 if ((traverse_mask & Traverse::traverse_functions) != 0)
4200 int t = traverse->function(p);
4201 if (t == TRAVERSE_EXIT)
4202 return TRAVERSE_EXIT;
4203 else if (t == TRAVERSE_SKIP_COMPONENTS)
4208 & (Traverse::traverse_variables
4209 | Traverse::traverse_constants
4210 | Traverse::traverse_functions
4211 | Traverse::traverse_blocks
4212 | Traverse::traverse_statements
4213 | Traverse::traverse_expressions
4214 | Traverse::traverse_types)) != 0)
4216 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4217 return TRAVERSE_EXIT;
4221 case Named_object::NAMED_OBJECT_PACKAGE:
4222 // These are traversed in Gogo::traverse.
4223 gcc_assert(is_global);
4226 case Named_object::NAMED_OBJECT_TYPE:
4227 if ((traverse_mask & Traverse::traverse_types) != 0
4228 || (traverse_mask & Traverse::traverse_expressions) != 0)
4230 if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4231 return TRAVERSE_EXIT;
4235 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4236 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4237 case Named_object::NAMED_OBJECT_UNKNOWN:
4240 case Named_object::NAMED_OBJECT_SINK:
4246 return TRAVERSE_CONTINUE;
4251 Package::Package(const std::string& name, const std::string& unique_prefix,
4252 source_location location)
4253 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4254 priority_(0), location_(location), used_(false), is_imported_(false),
4255 uses_sink_alias_(false)
4257 gcc_assert(!name.empty() && !unique_prefix.empty());
4260 // Set the priority. We may see multiple priorities for an imported
4261 // package; we want to use the largest one.
4264 Package::set_priority(int priority)
4266 if (priority > this->priority_)
4267 this->priority_ = priority;
4270 // Determine types of constants. Everything else in a package
4271 // (variables, function declarations) should already have a fixed
4272 // type. Constants may have abstract types.
4275 Package::determine_types()
4277 Bindings* bindings = this->bindings_;
4278 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4279 p != bindings->end_definitions();
4282 if ((*p)->is_const())
4283 (*p)->const_value()->determine_type();
4291 Traverse::~Traverse()
4293 if (this->types_seen_ != NULL)
4294 delete this->types_seen_;
4295 if (this->expressions_seen_ != NULL)
4296 delete this->expressions_seen_;
4299 // Record that we are looking at a type, and return true if we have
4303 Traverse::remember_type(const Type* type)
4305 if (type->is_error_type())
4307 gcc_assert((this->traverse_mask() & traverse_types) != 0
4308 || (this->traverse_mask() & traverse_expressions) != 0);
4309 // We only have to remember named types, as they are the only ones
4310 // we can see multiple times in a traversal.
4311 if (type->classification() != Type::TYPE_NAMED)
4313 if (this->types_seen_ == NULL)
4314 this->types_seen_ = new Types_seen();
4315 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4319 // Record that we are looking at an expression, and return true if we
4320 // have already seen it.
4323 Traverse::remember_expression(const Expression* expression)
4325 gcc_assert((this->traverse_mask() & traverse_types) != 0
4326 || (this->traverse_mask() & traverse_expressions) != 0);
4327 if (this->expressions_seen_ == NULL)
4328 this->expressions_seen_ = new Expressions_seen();
4329 std::pair<Expressions_seen::iterator, bool> ins =
4330 this->expressions_seen_->insert(expression);
4334 // The default versions of these functions should never be called: the
4335 // traversal mask indicates which functions may be called.
4338 Traverse::variable(Named_object*)
4344 Traverse::constant(Named_object*, bool)
4350 Traverse::function(Named_object*)
4356 Traverse::block(Block*)
4362 Traverse::statement(Block*, size_t*, Statement*)
4368 Traverse::expression(Expression**)
4374 Traverse::type(Type*)