1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
13 #include "statements.h"
14 #include "expressions.h"
22 Gogo::Gogo(int int_type_size, int pointer_size)
25 globals_(new Bindings(NULL)),
27 imported_unsafe_(false),
29 map_descriptors_(NULL),
30 type_descriptor_decls_(NULL),
36 unique_prefix_specified_(false),
38 named_types_are_converted_(false)
40 const source_location loc = BUILTINS_LOCATION;
42 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
43 RUNTIME_TYPE_KIND_UINT8);
44 this->add_named_type(uint8_type);
45 this->add_named_type(Type::make_integer_type("uint16", true, 16,
46 RUNTIME_TYPE_KIND_UINT16));
47 this->add_named_type(Type::make_integer_type("uint32", true, 32,
48 RUNTIME_TYPE_KIND_UINT32));
49 this->add_named_type(Type::make_integer_type("uint64", true, 64,
50 RUNTIME_TYPE_KIND_UINT64));
52 this->add_named_type(Type::make_integer_type("int8", false, 8,
53 RUNTIME_TYPE_KIND_INT8));
54 this->add_named_type(Type::make_integer_type("int16", false, 16,
55 RUNTIME_TYPE_KIND_INT16));
56 this->add_named_type(Type::make_integer_type("int32", false, 32,
57 RUNTIME_TYPE_KIND_INT32));
58 this->add_named_type(Type::make_integer_type("int64", false, 64,
59 RUNTIME_TYPE_KIND_INT64));
61 this->add_named_type(Type::make_float_type("float32", 32,
62 RUNTIME_TYPE_KIND_FLOAT32));
63 this->add_named_type(Type::make_float_type("float64", 64,
64 RUNTIME_TYPE_KIND_FLOAT64));
66 this->add_named_type(Type::make_complex_type("complex64", 64,
67 RUNTIME_TYPE_KIND_COMPLEX64));
68 this->add_named_type(Type::make_complex_type("complex128", 128,
69 RUNTIME_TYPE_KIND_COMPLEX128));
71 if (int_type_size < 32)
73 this->add_named_type(Type::make_integer_type("uint", true,
75 RUNTIME_TYPE_KIND_UINT));
76 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
77 RUNTIME_TYPE_KIND_INT);
78 this->add_named_type(int_type);
80 // "byte" is an alias for "uint8". Construct a Named_object which
81 // points to UINT8_TYPE. Note that this breaks the normal pairing
82 // in which a Named_object points to a Named_type which points back
83 // to the same Named_object.
84 Named_object* byte_type = this->declare_type("byte", loc);
85 byte_type->set_type_value(uint8_type);
87 this->add_named_type(Type::make_integer_type("uintptr", true,
89 RUNTIME_TYPE_KIND_UINTPTR));
91 this->add_named_type(Type::make_named_bool_type());
93 this->add_named_type(Type::make_named_string_type());
95 this->globals_->add_constant(Typed_identifier("true",
96 Type::make_boolean_type(),
99 Expression::make_boolean(true, loc),
101 this->globals_->add_constant(Typed_identifier("false",
102 Type::make_boolean_type(),
105 Expression::make_boolean(false, loc),
108 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
111 Expression::make_nil(loc),
114 Type* abstract_int_type = Type::make_abstract_integer_type();
115 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
118 Expression::make_iota(),
121 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
122 new_type->set_is_varargs();
123 new_type->set_is_builtin();
124 this->globals_->add_function_declaration("new", NULL, new_type, loc);
126 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
127 make_type->set_is_varargs();
128 make_type->set_is_builtin();
129 this->globals_->add_function_declaration("make", NULL, make_type, loc);
131 Typed_identifier_list* len_result = new Typed_identifier_list();
132 len_result->push_back(Typed_identifier("", int_type, loc));
133 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
135 len_type->set_is_builtin();
136 this->globals_->add_function_declaration("len", NULL, len_type, loc);
138 Typed_identifier_list* cap_result = new Typed_identifier_list();
139 cap_result->push_back(Typed_identifier("", int_type, loc));
140 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
142 cap_type->set_is_builtin();
143 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
145 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
146 print_type->set_is_varargs();
147 print_type->set_is_builtin();
148 this->globals_->add_function_declaration("print", NULL, print_type, loc);
150 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
151 print_type->set_is_varargs();
152 print_type->set_is_builtin();
153 this->globals_->add_function_declaration("println", NULL, print_type, loc);
155 Type *empty = Type::make_interface_type(NULL, loc);
156 Typed_identifier_list* panic_parms = new Typed_identifier_list();
157 panic_parms->push_back(Typed_identifier("e", empty, loc));
158 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
160 panic_type->set_is_builtin();
161 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
163 Typed_identifier_list* recover_result = new Typed_identifier_list();
164 recover_result->push_back(Typed_identifier("", empty, loc));
165 Function_type* recover_type = Type::make_function_type(NULL, NULL,
168 recover_type->set_is_builtin();
169 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
171 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
172 close_type->set_is_varargs();
173 close_type->set_is_builtin();
174 this->globals_->add_function_declaration("close", NULL, close_type, loc);
176 Typed_identifier_list* closed_result = new Typed_identifier_list();
177 closed_result->push_back(Typed_identifier("", Type::lookup_bool_type(),
179 Function_type* closed_type = Type::make_function_type(NULL, NULL,
181 closed_type->set_is_varargs();
182 closed_type->set_is_builtin();
183 this->globals_->add_function_declaration("closed", NULL, closed_type, loc);
185 Typed_identifier_list* copy_result = new Typed_identifier_list();
186 copy_result->push_back(Typed_identifier("", int_type, loc));
187 Function_type* copy_type = Type::make_function_type(NULL, NULL,
189 copy_type->set_is_varargs();
190 copy_type->set_is_builtin();
191 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
193 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
194 append_type->set_is_varargs();
195 append_type->set_is_builtin();
196 this->globals_->add_function_declaration("append", NULL, append_type, loc);
198 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
199 complex_type->set_is_varargs();
200 complex_type->set_is_builtin();
201 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
203 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
204 real_type->set_is_varargs();
205 real_type->set_is_builtin();
206 this->globals_->add_function_declaration("real", NULL, real_type, loc);
208 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
209 imag_type->set_is_varargs();
210 imag_type->set_is_builtin();
211 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
213 this->define_builtin_function_trees();
216 // Munge name for use in an error message.
219 Gogo::message_name(const std::string& name)
221 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
224 // Get the package name.
227 Gogo::package_name() const
229 gcc_assert(this->package_ != NULL);
230 return this->package_->name();
233 // Set the package name.
236 Gogo::set_package_name(const std::string& package_name,
237 source_location location)
239 if (this->package_ != NULL && this->package_->name() != package_name)
241 error_at(location, "expected package %<%s%>",
242 Gogo::message_name(this->package_->name()).c_str());
246 // If the user did not specify a unique prefix, we always use "go".
247 // This in effect requires that the package name be unique.
248 if (this->unique_prefix_.empty())
249 this->unique_prefix_ = "go";
251 this->package_ = this->register_package(package_name, this->unique_prefix_,
254 // We used to permit people to qualify symbols with the current
255 // package name (e.g., P.x), but we no longer do.
256 // this->globals_->add_package(package_name, this->package_);
258 if (this->is_main_package())
260 // Declare "main" as a function which takes no parameters and
262 this->declare_function("main",
263 Type::make_function_type(NULL, NULL, NULL,
269 // Return whether this is the "main" package. This is not true if
270 // -fgo-prefix was used.
273 Gogo::is_main_package() const
275 return this->package_name() == "main" && !this->unique_prefix_specified_;
281 Gogo::import_package(const std::string& filename,
282 const std::string& local_name,
283 bool is_local_name_exported,
284 source_location location)
286 if (filename == "unsafe")
288 this->import_unsafe(local_name, is_local_name_exported, location);
292 Imports::const_iterator p = this->imports_.find(filename);
293 if (p != this->imports_.end())
295 Package* package = p->second;
296 package->set_location(location);
297 package->set_is_imported();
298 std::string ln = local_name;
299 bool is_ln_exported = is_local_name_exported;
302 ln = package->name();
303 is_ln_exported = Lex::is_exported_name(ln);
307 Bindings* bindings = package->bindings();
308 for (Bindings::const_declarations_iterator p =
309 bindings->begin_declarations();
310 p != bindings->end_declarations();
312 this->add_named_object(p->second);
315 package->set_uses_sink_alias();
318 ln = this->pack_hidden_name(ln, is_ln_exported);
319 this->package_->bindings()->add_package(ln, package);
324 Import::Stream* stream = Import::open_package(filename, location);
327 error_at(location, "import file %qs not found", filename.c_str());
331 Import imp(stream, location);
332 imp.register_builtin_types(this);
333 Package* package = imp.import(this, local_name, is_local_name_exported);
336 if (package->name() == this->package_name()
337 && package->unique_prefix() == this->unique_prefix())
339 ("imported package uses same package name and prefix "
340 "as package being compiled (see -fgo-prefix option)"));
342 this->imports_.insert(std::make_pair(filename, package));
343 package->set_is_imported();
349 // Add an import control function for an imported package to the list.
352 Gogo::add_import_init_fn(const std::string& package_name,
353 const std::string& init_name, int prio)
355 for (std::set<Import_init>::const_iterator p =
356 this->imported_init_fns_.begin();
357 p != this->imported_init_fns_.end();
360 if (p->init_name() == init_name
361 && (p->package_name() != package_name || p->priority() != prio))
363 error("duplicate package initialization name %qs",
364 Gogo::message_name(init_name).c_str());
365 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
366 Gogo::message_name(p->package_name()).c_str(),
368 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
369 Gogo::message_name(package_name).c_str(), prio);
374 this->imported_init_fns_.insert(Import_init(package_name, init_name,
378 // Return whether we are at the global binding level.
381 Gogo::in_global_scope() const
383 return this->functions_.empty();
386 // Return the current binding contour.
389 Gogo::current_bindings()
391 if (!this->functions_.empty())
392 return this->functions_.back().blocks.back()->bindings();
393 else if (this->package_ != NULL)
394 return this->package_->bindings();
396 return this->globals_;
400 Gogo::current_bindings() const
402 if (!this->functions_.empty())
403 return this->functions_.back().blocks.back()->bindings();
404 else if (this->package_ != NULL)
405 return this->package_->bindings();
407 return this->globals_;
410 // Return the current block.
413 Gogo::current_block()
415 if (this->functions_.empty())
418 return this->functions_.back().blocks.back();
421 // Look up a name in the current binding contour. If PFUNCTION is not
422 // NULL, set it to the function in which the name is defined, or NULL
423 // if the name is defined in global scope.
426 Gogo::lookup(const std::string& name, Named_object** pfunction) const
428 if (pfunction != NULL)
431 if (Gogo::is_sink_name(name))
432 return Named_object::make_sink();
434 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
435 p != this->functions_.rend();
438 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
441 if (pfunction != NULL)
442 *pfunction = p->function;
447 if (this->package_ != NULL)
449 Named_object* ret = this->package_->bindings()->lookup(name);
452 if (ret->package() != NULL)
453 ret->package()->set_used();
458 // We do not look in the global namespace. If we did, the global
459 // namespace would effectively hide names which were defined in
460 // package scope which we have not yet seen. Instead,
461 // define_global_names is called after parsing is over to connect
462 // undefined names at package scope with names defined at global
468 // Look up a name in the current block, without searching enclosing
472 Gogo::lookup_in_block(const std::string& name) const
474 gcc_assert(!this->functions_.empty());
475 gcc_assert(!this->functions_.back().blocks.empty());
476 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
479 // Look up a name in the global namespace.
482 Gogo::lookup_global(const char* name) const
484 return this->globals_->lookup(name);
487 // Add an imported package.
490 Gogo::add_imported_package(const std::string& real_name,
491 const std::string& alias_arg,
492 bool is_alias_exported,
493 const std::string& unique_prefix,
494 source_location location,
495 bool* padd_to_globals)
497 // FIXME: Now that we compile packages as a whole, should we permit
498 // importing the current package?
499 if (this->package_name() == real_name
500 && this->unique_prefix() == unique_prefix)
502 *padd_to_globals = false;
503 if (!alias_arg.empty() && alias_arg != ".")
505 std::string alias = this->pack_hidden_name(alias_arg,
507 this->package_->bindings()->add_package(alias, this->package_);
509 return this->package_;
511 else if (alias_arg == ".")
513 *padd_to_globals = true;
514 return this->register_package(real_name, unique_prefix, location);
516 else if (alias_arg == "_")
518 Package* ret = this->register_package(real_name, unique_prefix, location);
519 ret->set_uses_sink_alias();
524 *padd_to_globals = false;
525 std::string alias = alias_arg;
529 is_alias_exported = Lex::is_exported_name(alias);
531 alias = this->pack_hidden_name(alias, is_alias_exported);
532 Named_object* no = this->add_package(real_name, alias, unique_prefix,
534 if (!no->is_package())
536 return no->package_value();
543 Gogo::add_package(const std::string& real_name, const std::string& alias,
544 const std::string& unique_prefix, source_location location)
546 gcc_assert(this->in_global_scope());
548 // Register the package. Note that we might have already seen it in
549 // an earlier import.
550 Package* package = this->register_package(real_name, unique_prefix, location);
552 return this->package_->bindings()->add_package(alias, package);
555 // Register a package. This package may or may not be imported. This
556 // returns the Package structure for the package, creating if it
560 Gogo::register_package(const std::string& package_name,
561 const std::string& unique_prefix,
562 source_location location)
564 gcc_assert(!unique_prefix.empty() && !package_name.empty());
565 std::string name = unique_prefix + '.' + package_name;
566 Package* package = NULL;
567 std::pair<Packages::iterator, bool> ins =
568 this->packages_.insert(std::make_pair(name, package));
571 // We have seen this package name before.
572 package = ins.first->second;
573 gcc_assert(package != NULL);
574 gcc_assert(package->name() == package_name
575 && package->unique_prefix() == unique_prefix);
576 if (package->location() == UNKNOWN_LOCATION)
577 package->set_location(location);
581 // First time we have seen this package name.
582 package = new Package(package_name, unique_prefix, location);
583 gcc_assert(ins.first->second == NULL);
584 ins.first->second = package;
590 // Start compiling a function.
593 Gogo::start_function(const std::string& name, Function_type* type,
594 bool add_method_to_type, source_location location)
596 bool at_top_level = this->functions_.empty();
598 Block* block = new Block(NULL, location);
600 Function* enclosing = (at_top_level
602 : this->functions_.back().function->func_value());
604 Function* function = new Function(type, enclosing, block, location);
606 if (type->is_method())
608 const Typed_identifier* receiver = type->receiver();
609 Variable* this_param = new Variable(receiver->type(), NULL, false,
610 true, true, location);
611 std::string name = receiver->name();
614 // We need to give receivers a name since they wind up in
615 // DECL_ARGUMENTS. FIXME.
616 static unsigned int count;
618 snprintf(buf, sizeof buf, "r.%u", count);
622 block->bindings()->add_variable(name, NULL, this_param);
625 const Typed_identifier_list* parameters = type->parameters();
626 bool is_varargs = type->is_varargs();
627 if (parameters != NULL)
629 for (Typed_identifier_list::const_iterator p = parameters->begin();
630 p != parameters->end();
633 Variable* param = new Variable(p->type(), NULL, false, true, false,
635 if (is_varargs && p + 1 == parameters->end())
636 param->set_is_varargs_parameter();
638 std::string name = p->name();
639 if (name.empty() || Gogo::is_sink_name(name))
641 // We need to give parameters a name since they wind up
642 // in DECL_ARGUMENTS. FIXME.
643 static unsigned int count;
645 snprintf(buf, sizeof buf, "p.%u", count);
649 block->bindings()->add_variable(name, NULL, param);
653 function->create_named_result_variables(this);
655 const std::string* pname;
656 std::string nested_name;
657 bool is_init = false;
658 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
660 if ((type->parameters() != NULL && !type->parameters()->empty())
661 || (type->results() != NULL && !type->results()->empty()))
663 "func init must have no arguments and no return values");
664 // There can be multiple "init" functions, so give them each a
666 static int init_count;
668 snprintf(buf, sizeof buf, ".$init%d", init_count);
671 pname = &nested_name;
674 else if (!name.empty())
678 // Invent a name for a nested function.
679 static int nested_count;
681 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
684 pname = &nested_name;
688 if (Gogo::is_sink_name(*pname))
690 static int sink_count;
692 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
694 ret = Named_object::make_function(buf, NULL, function);
696 else if (!type->is_method())
698 ret = this->package_->bindings()->add_function(*pname, NULL, function);
699 if (!ret->is_function() || ret->func_value() != function)
701 // Redefinition error. Invent a name to avoid knockon
703 static int redefinition_count;
705 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
706 ++redefinition_count;
707 ret = this->package_->bindings()->add_function(buf, NULL, function);
712 if (!add_method_to_type)
713 ret = Named_object::make_function(name, NULL, function);
716 gcc_assert(at_top_level);
717 Type* rtype = type->receiver()->type();
719 // We want to look through the pointer created by the
720 // parser, without getting an error if the type is not yet
722 if (rtype->classification() == Type::TYPE_POINTER)
723 rtype = rtype->points_to();
725 if (rtype->is_error_type())
726 ret = Named_object::make_function(name, NULL, function);
727 else if (rtype->named_type() != NULL)
729 ret = rtype->named_type()->add_method(name, function);
730 if (!ret->is_function())
732 // Redefinition error.
733 ret = Named_object::make_function(name, NULL, function);
736 else if (rtype->forward_declaration_type() != NULL)
738 Named_object* type_no =
739 rtype->forward_declaration_type()->named_object();
740 if (type_no->is_unknown())
742 // If we are seeing methods it really must be a
743 // type. Declare it as such. An alternative would
744 // be to support lists of methods for unknown
745 // expressions. Either way the error messages if
746 // this is not a type are going to get confusing.
747 Named_object* declared =
748 this->declare_package_type(type_no->name(),
749 type_no->location());
751 == type_no->unknown_value()->real_named_object());
753 ret = rtype->forward_declaration_type()->add_method(name,
759 this->package_->bindings()->add_method(ret);
762 this->functions_.resize(this->functions_.size() + 1);
763 Open_function& of(this->functions_.back());
765 of.blocks.push_back(block);
769 this->init_functions_.push_back(ret);
770 this->need_init_fn_ = true;
776 // Finish compiling a function.
779 Gogo::finish_function(source_location location)
781 this->finish_block(location);
782 gcc_assert(this->functions_.back().blocks.empty());
783 this->functions_.pop_back();
786 // Return the current function.
789 Gogo::current_function() const
791 gcc_assert(!this->functions_.empty());
792 return this->functions_.back().function;
795 // Start a new block.
798 Gogo::start_block(source_location location)
800 gcc_assert(!this->functions_.empty());
801 Block* block = new Block(this->current_block(), location);
802 this->functions_.back().blocks.push_back(block);
808 Gogo::finish_block(source_location location)
810 gcc_assert(!this->functions_.empty());
811 gcc_assert(!this->functions_.back().blocks.empty());
812 Block* block = this->functions_.back().blocks.back();
813 this->functions_.back().blocks.pop_back();
814 block->set_end_location(location);
818 // Add an unknown name.
821 Gogo::add_unknown_name(const std::string& name, source_location location)
823 return this->package_->bindings()->add_unknown_name(name, location);
826 // Declare a function.
829 Gogo::declare_function(const std::string& name, Function_type* type,
830 source_location location)
832 if (!type->is_method())
833 return this->current_bindings()->add_function_declaration(name, NULL, type,
837 // We don't bother to add this to the list of global
839 Type* rtype = type->receiver()->type();
841 // We want to look through the pointer created by the
842 // parser, without getting an error if the type is not yet
844 if (rtype->classification() == Type::TYPE_POINTER)
845 rtype = rtype->points_to();
847 if (rtype->is_error_type())
849 else if (rtype->named_type() != NULL)
850 return rtype->named_type()->add_method_declaration(name, NULL, type,
852 else if (rtype->forward_declaration_type() != NULL)
854 Forward_declaration_type* ftype = rtype->forward_declaration_type();
855 return ftype->add_method_declaration(name, type, location);
862 // Add a label definition.
865 Gogo::add_label_definition(const std::string& label_name,
866 source_location location)
868 gcc_assert(!this->functions_.empty());
869 Function* func = this->functions_.back().function->func_value();
870 Label* label = func->add_label_definition(label_name, location);
871 this->add_statement(Statement::make_label_statement(label, location));
875 // Add a label reference.
878 Gogo::add_label_reference(const std::string& label_name)
880 gcc_assert(!this->functions_.empty());
881 Function* func = this->functions_.back().function->func_value();
882 return func->add_label_reference(label_name);
888 Gogo::add_statement(Statement* statement)
890 gcc_assert(!this->functions_.empty()
891 && !this->functions_.back().blocks.empty());
892 this->functions_.back().blocks.back()->add_statement(statement);
898 Gogo::add_block(Block* block, source_location location)
900 gcc_assert(!this->functions_.empty()
901 && !this->functions_.back().blocks.empty());
902 Statement* statement = Statement::make_block_statement(block, location);
903 this->functions_.back().blocks.back()->add_statement(statement);
909 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
912 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
918 Gogo::add_type(const std::string& name, Type* type, source_location location)
920 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
922 if (!this->in_global_scope() && no->is_type())
923 no->type_value()->set_in_function(this->functions_.back().function);
929 Gogo::add_named_type(Named_type* type)
931 gcc_assert(this->in_global_scope());
932 this->current_bindings()->add_named_type(type);
938 Gogo::declare_type(const std::string& name, source_location location)
940 Bindings* bindings = this->current_bindings();
941 Named_object* no = bindings->add_type_declaration(name, NULL, location);
942 if (!this->in_global_scope() && no->is_type_declaration())
944 Named_object* f = this->functions_.back().function;
945 no->type_declaration_value()->set_in_function(f);
950 // Declare a type at the package level.
953 Gogo::declare_package_type(const std::string& name, source_location location)
955 return this->package_->bindings()->add_type_declaration(name, NULL, location);
958 // Define a type which was already declared.
961 Gogo::define_type(Named_object* no, Named_type* type)
963 this->current_bindings()->define_type(no, type);
969 Gogo::add_variable(const std::string& name, Variable* variable)
971 Named_object* no = this->current_bindings()->add_variable(name, NULL,
974 // In a function the middle-end wants to see a DECL_EXPR node.
977 && !no->var_value()->is_parameter()
978 && !this->functions_.empty())
979 this->add_statement(Statement::make_variable_declaration(no));
984 // Add a sink--a reference to the blank identifier _.
989 return Named_object::make_sink();
992 // Add a named object.
995 Gogo::add_named_object(Named_object* no)
997 this->current_bindings()->add_named_object(no);
1000 // Record that we've seen an interface type.
1003 Gogo::record_interface_type(Interface_type* itype)
1005 this->interface_types_.push_back(itype);
1008 // Return a name for a thunk object.
1013 static int thunk_count;
1014 char thunk_name[50];
1015 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1020 // Return whether a function is a thunk.
1023 Gogo::is_thunk(const Named_object* no)
1025 return no->name().compare(0, 6, "$thunk") == 0;
1028 // Define the global names. We do this only after parsing all the
1029 // input files, because the program might define the global names
1033 Gogo::define_global_names()
1035 for (Bindings::const_declarations_iterator p =
1036 this->globals_->begin_declarations();
1037 p != this->globals_->end_declarations();
1040 Named_object* global_no = p->second;
1041 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1042 Named_object* no = this->package_->bindings()->lookup(name);
1046 if (no->is_type_declaration())
1048 if (global_no->is_type())
1050 if (no->type_declaration_value()->has_methods())
1051 error_at(no->location(),
1052 "may not define methods for global type");
1053 no->set_type_value(global_no->type_value());
1057 error_at(no->location(), "expected type");
1058 Type* errtype = Type::make_error_type();
1059 Named_object* err = Named_object::make_type("error", NULL,
1062 no->set_type_value(err->type_value());
1065 else if (no->is_unknown())
1066 no->unknown_value()->set_real_named_object(global_no);
1070 // Clear out names in file scope.
1073 Gogo::clear_file_scope()
1075 this->package_->bindings()->clear_file_scope();
1077 // Warn about packages which were imported but not used.
1078 for (Packages::iterator p = this->packages_.begin();
1079 p != this->packages_.end();
1082 Package* package = p->second;
1083 if (package != this->package_
1084 && package->is_imported()
1086 && !package->uses_sink_alias()
1088 error_at(package->location(), "imported and not used: %s",
1089 Gogo::message_name(package->name()).c_str());
1090 package->clear_is_imported();
1091 package->clear_uses_sink_alias();
1092 package->clear_used();
1096 // Traverse the tree.
1099 Gogo::traverse(Traverse* traverse)
1101 // Traverse the current package first for consistency. The other
1102 // packages will only contain imported types, constants, and
1104 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1106 for (Packages::const_iterator p = this->packages_.begin();
1107 p != this->packages_.end();
1110 if (p->second != this->package_)
1112 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1118 // Traversal class used to verify types.
1120 class Verify_types : public Traverse
1124 : Traverse(traverse_types)
1131 // Verify that a type is correct.
1134 Verify_types::type(Type* t)
1137 return TRAVERSE_SKIP_COMPONENTS;
1138 return TRAVERSE_CONTINUE;
1141 // Verify that all types are correct.
1144 Gogo::verify_types()
1146 Verify_types traverse;
1147 this->traverse(&traverse);
1150 // Traversal class used to lower parse tree.
1152 class Lower_parse_tree : public Traverse
1155 Lower_parse_tree(Gogo* gogo, Named_object* function)
1156 : Traverse(traverse_variables
1157 | traverse_constants
1158 | traverse_functions
1159 | traverse_statements
1160 | traverse_expressions),
1161 gogo_(gogo), function_(function), iota_value_(-1)
1165 variable(Named_object*);
1168 constant(Named_object*, bool);
1171 function(Named_object*);
1174 statement(Block*, size_t* pindex, Statement*);
1177 expression(Expression**);
1182 // The function we are traversing.
1183 Named_object* function_;
1184 // Value to use for the predeclared constant iota.
1188 // Lower variables. We handle variables specially to break loops in
1189 // which a variable initialization expression refers to itself. The
1190 // loop breaking is in lower_init_expression.
1193 Lower_parse_tree::variable(Named_object* no)
1195 if (no->is_variable())
1196 no->var_value()->lower_init_expression(this->gogo_, this->function_);
1197 return TRAVERSE_CONTINUE;
1200 // Lower constants. We handle constants specially so that we can set
1201 // the right value for the predeclared constant iota. This works in
1202 // conjunction with the way we lower Const_expression objects.
1205 Lower_parse_tree::constant(Named_object* no, bool)
1207 Named_constant* nc = no->const_value();
1209 // Don't get into trouble if the constant's initializer expression
1210 // refers to the constant itself.
1212 return TRAVERSE_CONTINUE;
1215 gcc_assert(this->iota_value_ == -1);
1216 this->iota_value_ = nc->iota_value();
1217 nc->traverse_expression(this);
1218 this->iota_value_ = -1;
1220 nc->clear_lowering();
1222 // We will traverse the expression a second time, but that will be
1225 return TRAVERSE_CONTINUE;
1228 // Lower function closure types. Record the function while lowering
1229 // it, so that we can pass it down when lowering an expression.
1232 Lower_parse_tree::function(Named_object* no)
1234 no->func_value()->set_closure_type();
1236 gcc_assert(this->function_ == NULL);
1237 this->function_ = no;
1238 int t = no->func_value()->traverse(this);
1239 this->function_ = NULL;
1241 if (t == TRAVERSE_EXIT)
1243 return TRAVERSE_SKIP_COMPONENTS;
1246 // Lower statement parse trees.
1249 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1251 // Lower the expressions first.
1252 int t = sorig->traverse_contents(this);
1253 if (t == TRAVERSE_EXIT)
1256 // Keep lowering until nothing changes.
1257 Statement* s = sorig;
1260 Statement* snew = s->lower(this->gogo_, block);
1264 t = s->traverse_contents(this);
1265 if (t == TRAVERSE_EXIT)
1270 block->replace_statement(*pindex, s);
1272 return TRAVERSE_SKIP_COMPONENTS;
1275 // Lower expression parse trees.
1278 Lower_parse_tree::expression(Expression** pexpr)
1280 // We have to lower all subexpressions first, so that we can get
1281 // their type if necessary. This is awkward, because we don't have
1282 // a postorder traversal pass.
1283 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1284 return TRAVERSE_EXIT;
1285 // Keep lowering until nothing changes.
1288 Expression* e = *pexpr;
1289 Expression* enew = e->lower(this->gogo_, this->function_,
1295 return TRAVERSE_SKIP_COMPONENTS;
1298 // Lower the parse tree. This is called after the parse is complete,
1299 // when all names should be resolved.
1302 Gogo::lower_parse_tree()
1304 Lower_parse_tree lower_parse_tree(this, NULL);
1305 this->traverse(&lower_parse_tree);
1308 // Lower an expression.
1311 Gogo::lower_expression(Named_object* function, Expression** pexpr)
1313 Lower_parse_tree lower_parse_tree(this, function);
1314 lower_parse_tree.expression(pexpr);
1317 // Lower a constant. This is called when lowering a reference to a
1318 // constant. We have to make sure that the constant has already been
1322 Gogo::lower_constant(Named_object* no)
1324 gcc_assert(no->is_const());
1325 Lower_parse_tree lower(this, NULL);
1326 lower.constant(no, false);
1329 // Look for interface types to finalize methods of inherited
1332 class Finalize_methods : public Traverse
1335 Finalize_methods(Gogo* gogo)
1336 : Traverse(traverse_types),
1347 // Finalize the methods of an interface type.
1350 Finalize_methods::type(Type* t)
1352 // Check the classification so that we don't finalize the methods
1353 // twice for a named interface type.
1354 switch (t->classification())
1356 case Type::TYPE_INTERFACE:
1357 t->interface_type()->finalize_methods();
1360 case Type::TYPE_NAMED:
1362 // We have to finalize the methods of the real type first.
1363 // But if the real type is a struct type, then we only want to
1364 // finalize the methods of the field types, not of the struct
1365 // type itself. We don't want to add methods to the struct,
1366 // since it has a name.
1367 Type* rt = t->named_type()->real_type();
1368 if (rt->classification() != Type::TYPE_STRUCT)
1370 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1371 return TRAVERSE_EXIT;
1375 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1376 return TRAVERSE_EXIT;
1379 t->named_type()->finalize_methods(this->gogo_);
1381 return TRAVERSE_SKIP_COMPONENTS;
1384 case Type::TYPE_STRUCT:
1385 t->struct_type()->finalize_methods(this->gogo_);
1392 return TRAVERSE_CONTINUE;
1395 // Finalize method lists and build stub methods for types.
1398 Gogo::finalize_methods()
1400 Finalize_methods finalize(this);
1401 this->traverse(&finalize);
1404 // Set types for unspecified variables and constants.
1407 Gogo::determine_types()
1409 Bindings* bindings = this->current_bindings();
1410 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1411 p != bindings->end_definitions();
1414 if ((*p)->is_function())
1415 (*p)->func_value()->determine_types();
1416 else if ((*p)->is_variable())
1417 (*p)->var_value()->determine_type();
1418 else if ((*p)->is_const())
1419 (*p)->const_value()->determine_type();
1421 // See if a variable requires us to build an initialization
1422 // function. We know that we will see all global variables
1424 if (!this->need_init_fn_ && (*p)->is_variable())
1426 Variable* variable = (*p)->var_value();
1428 // If this is a global variable which requires runtime
1429 // initialization, we need an initialization function.
1430 if (!variable->is_global())
1432 else if (variable->init() == NULL)
1434 else if (variable->type()->interface_type() != NULL)
1435 this->need_init_fn_ = true;
1436 else if (variable->init()->is_constant())
1438 else if (!variable->init()->is_composite_literal())
1439 this->need_init_fn_ = true;
1440 else if (variable->init()->is_nonconstant_composite_literal())
1441 this->need_init_fn_ = true;
1443 // If this is a global variable which holds a pointer value,
1444 // then we need an initialization function to register it as a
1446 if (variable->is_global() && variable->type()->has_pointer())
1447 this->need_init_fn_ = true;
1451 // Determine the types of constants in packages.
1452 for (Packages::const_iterator p = this->packages_.begin();
1453 p != this->packages_.end();
1455 p->second->determine_types();
1458 // Traversal class used for type checking.
1460 class Check_types_traverse : public Traverse
1463 Check_types_traverse(Gogo* gogo)
1464 : Traverse(traverse_variables
1465 | traverse_constants
1466 | traverse_statements
1467 | traverse_expressions),
1472 variable(Named_object*);
1475 constant(Named_object*, bool);
1478 statement(Block*, size_t* pindex, Statement*);
1481 expression(Expression**);
1488 // Check that a variable initializer has the right type.
1491 Check_types_traverse::variable(Named_object* named_object)
1493 if (named_object->is_variable())
1495 Variable* var = named_object->var_value();
1496 Expression* init = var->init();
1499 && !Type::are_assignable(var->type(), init->type(), &reason))
1502 error_at(var->location(), "incompatible type in initialization");
1504 error_at(var->location(),
1505 "incompatible type in initialization (%s)",
1510 return TRAVERSE_CONTINUE;
1513 // Check that a constant initializer has the right type.
1516 Check_types_traverse::constant(Named_object* named_object, bool)
1518 Named_constant* constant = named_object->const_value();
1519 Type* ctype = constant->type();
1520 if (ctype->integer_type() == NULL
1521 && ctype->float_type() == NULL
1522 && ctype->complex_type() == NULL
1523 && !ctype->is_boolean_type()
1524 && !ctype->is_string_type())
1526 if (!ctype->is_error_type())
1527 error_at(constant->location(), "invalid constant type");
1528 constant->set_error();
1530 else if (!constant->expr()->is_constant())
1532 error_at(constant->expr()->location(), "expression is not constant");
1533 constant->set_error();
1535 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1538 error_at(constant->location(),
1539 "initialization expression has wrong type");
1540 constant->set_error();
1542 return TRAVERSE_CONTINUE;
1545 // Check that types are valid in a statement.
1548 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1550 s->check_types(this->gogo_);
1551 return TRAVERSE_CONTINUE;
1554 // Check that types are valid in an expression.
1557 Check_types_traverse::expression(Expression** expr)
1559 (*expr)->check_types(this->gogo_);
1560 return TRAVERSE_CONTINUE;
1563 // Check that types are valid.
1568 Check_types_traverse traverse(this);
1569 this->traverse(&traverse);
1572 // Check the types in a single block.
1575 Gogo::check_types_in_block(Block* block)
1577 Check_types_traverse traverse(this);
1578 block->traverse(&traverse);
1581 // A traversal class used to find a single shortcut operator within an
1584 class Find_shortcut : public Traverse
1588 : Traverse(traverse_blocks
1589 | traverse_statements
1590 | traverse_expressions),
1594 // A pointer to the expression which was found, or NULL if none was
1598 { return this->found_; }
1603 { return TRAVERSE_SKIP_COMPONENTS; }
1606 statement(Block*, size_t*, Statement*)
1607 { return TRAVERSE_SKIP_COMPONENTS; }
1610 expression(Expression**);
1613 Expression** found_;
1616 // Find a shortcut expression.
1619 Find_shortcut::expression(Expression** pexpr)
1621 Expression* expr = *pexpr;
1622 Binary_expression* be = expr->binary_expression();
1624 return TRAVERSE_CONTINUE;
1625 Operator op = be->op();
1626 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1627 return TRAVERSE_CONTINUE;
1628 gcc_assert(this->found_ == NULL);
1629 this->found_ = pexpr;
1630 return TRAVERSE_EXIT;
1633 // A traversal class used to turn shortcut operators into explicit if
1636 class Shortcuts : public Traverse
1639 Shortcuts(Gogo* gogo)
1640 : Traverse(traverse_variables
1641 | traverse_statements),
1647 variable(Named_object*);
1650 statement(Block*, size_t*, Statement*);
1653 // Convert a shortcut operator.
1655 convert_shortcut(Block* enclosing, Expression** pshortcut);
1661 // Remove shortcut operators in a single statement.
1664 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1666 // FIXME: This approach doesn't work for switch statements, because
1667 // we add the new statements before the whole switch when we need to
1668 // instead add them just before the switch expression. The right
1669 // fix is probably to lower switch statements with nonconstant cases
1670 // to a series of conditionals.
1671 if (s->switch_statement() != NULL)
1672 return TRAVERSE_CONTINUE;
1676 Find_shortcut find_shortcut;
1678 // If S is a variable declaration, then ordinary traversal won't
1679 // do anything. We want to explicitly traverse the
1680 // initialization expression if there is one.
1681 Variable_declaration_statement* vds = s->variable_declaration_statement();
1682 Expression* init = NULL;
1684 s->traverse_contents(&find_shortcut);
1687 init = vds->var()->var_value()->init();
1689 return TRAVERSE_CONTINUE;
1690 init->traverse(&init, &find_shortcut);
1692 Expression** pshortcut = find_shortcut.found();
1693 if (pshortcut == NULL)
1694 return TRAVERSE_CONTINUE;
1696 Statement* snew = this->convert_shortcut(block, pshortcut);
1697 block->insert_statement_before(*pindex, snew);
1700 if (pshortcut == &init)
1701 vds->var()->var_value()->set_init(init);
1705 // Remove shortcut operators in the initializer of a global variable.
1708 Shortcuts::variable(Named_object* no)
1710 if (no->is_result_variable())
1711 return TRAVERSE_CONTINUE;
1712 Variable* var = no->var_value();
1713 Expression* init = var->init();
1714 if (!var->is_global() || init == NULL)
1715 return TRAVERSE_CONTINUE;
1719 Find_shortcut find_shortcut;
1720 init->traverse(&init, &find_shortcut);
1721 Expression** pshortcut = find_shortcut.found();
1722 if (pshortcut == NULL)
1723 return TRAVERSE_CONTINUE;
1725 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1726 var->add_preinit_statement(this->gogo_, snew);
1727 if (pshortcut == &init)
1728 var->set_init(init);
1732 // Given an expression which uses a shortcut operator, return a
1733 // statement which implements it, and update *PSHORTCUT accordingly.
1736 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1738 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1739 Expression* left = shortcut->left();
1740 Expression* right = shortcut->right();
1741 source_location loc = shortcut->location();
1743 Block* retblock = new Block(enclosing, loc);
1744 retblock->set_end_location(loc);
1746 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
1748 retblock->add_statement(ts);
1750 Block* block = new Block(retblock, loc);
1751 block->set_end_location(loc);
1752 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1753 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1754 block->add_statement(assign);
1756 Expression* cond = Expression::make_temporary_reference(ts, loc);
1757 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1758 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1760 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1762 retblock->add_statement(if_statement);
1764 *pshortcut = Expression::make_temporary_reference(ts, loc);
1768 // Now convert any shortcut operators in LEFT and RIGHT.
1769 Shortcuts shortcuts(this->gogo_);
1770 retblock->traverse(&shortcuts);
1772 return Statement::make_block_statement(retblock, loc);
1775 // Turn shortcut operators into explicit if statements. Doing this
1776 // considerably simplifies the order of evaluation rules.
1779 Gogo::remove_shortcuts()
1781 Shortcuts shortcuts(this);
1782 this->traverse(&shortcuts);
1785 // A traversal class which finds all the expressions which must be
1786 // evaluated in order within a statement or larger expression. This
1787 // is used to implement the rules about order of evaluation.
1789 class Find_eval_ordering : public Traverse
1792 typedef std::vector<Expression**> Expression_pointers;
1795 Find_eval_ordering()
1796 : Traverse(traverse_blocks
1797 | traverse_statements
1798 | traverse_expressions),
1804 { return this->exprs_.size(); }
1806 typedef Expression_pointers::const_iterator const_iterator;
1810 { return this->exprs_.begin(); }
1814 { return this->exprs_.end(); }
1819 { return TRAVERSE_SKIP_COMPONENTS; }
1822 statement(Block*, size_t*, Statement*)
1823 { return TRAVERSE_SKIP_COMPONENTS; }
1826 expression(Expression**);
1829 // A list of pointers to expressions with side-effects.
1830 Expression_pointers exprs_;
1833 // If an expression must be evaluated in order, put it on the list.
1836 Find_eval_ordering::expression(Expression** expression_pointer)
1838 // We have to look at subexpressions before this one.
1839 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1840 return TRAVERSE_EXIT;
1841 if ((*expression_pointer)->must_eval_in_order())
1842 this->exprs_.push_back(expression_pointer);
1843 return TRAVERSE_SKIP_COMPONENTS;
1846 // A traversal class for ordering evaluations.
1848 class Order_eval : public Traverse
1851 Order_eval(Gogo* gogo)
1852 : Traverse(traverse_variables
1853 | traverse_statements),
1858 variable(Named_object*);
1861 statement(Block*, size_t*, Statement*);
1868 // Implement the order of evaluation rules for a statement.
1871 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1873 // FIXME: This approach doesn't work for switch statements, because
1874 // we add the new statements before the whole switch when we need to
1875 // instead add them just before the switch expression. The right
1876 // fix is probably to lower switch statements with nonconstant cases
1877 // to a series of conditionals.
1878 if (s->switch_statement() != NULL)
1879 return TRAVERSE_CONTINUE;
1881 Find_eval_ordering find_eval_ordering;
1883 // If S is a variable declaration, then ordinary traversal won't do
1884 // anything. We want to explicitly traverse the initialization
1885 // expression if there is one.
1886 Variable_declaration_statement* vds = s->variable_declaration_statement();
1887 Expression* init = NULL;
1888 Expression* orig_init = NULL;
1890 s->traverse_contents(&find_eval_ordering);
1893 init = vds->var()->var_value()->init();
1895 return TRAVERSE_CONTINUE;
1898 // It might seem that this could be
1899 // init->traverse_subexpressions. Unfortunately that can fail
1902 // newvar, err := call(arg())
1903 // Here newvar will have an init of call result 0 of
1904 // call(arg()). If we only traverse subexpressions, we will
1905 // only find arg(), and we won't bother to move anything out.
1906 // Then we get to the assignment to err, we will traverse the
1907 // whole statement, and this time we will find both call() and
1908 // arg(), and so we will move them out. This will cause them to
1909 // be put into temporary variables before the assignment to err
1910 // but after the declaration of newvar. To avoid that problem,
1911 // we traverse the entire expression here.
1912 Expression::traverse(&init, &find_eval_ordering);
1915 if (find_eval_ordering.size() <= 1)
1917 // If there is only one expression with a side-effect, we can
1918 // leave it in place.
1919 return TRAVERSE_CONTINUE;
1922 bool is_thunk = s->thunk_statement() != NULL;
1923 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1924 p != find_eval_ordering.end();
1927 Expression** pexpr = *p;
1929 // If the last expression is a send or receive expression, we
1930 // may be ignoring the value; we don't want to evaluate it
1932 if (p + 1 == find_eval_ordering.end()
1933 && ((*pexpr)->classification() == Expression::EXPRESSION_SEND
1934 || (*pexpr)->classification() == Expression::EXPRESSION_RECEIVE))
1937 // The last expression in a thunk will be the call passed to go
1938 // or defer, which we must not evaluate early.
1939 if (is_thunk && p + 1 == find_eval_ordering.end())
1942 source_location loc = (*pexpr)->location();
1943 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1944 block->insert_statement_before(*pindex, ts);
1947 *pexpr = Expression::make_temporary_reference(ts, loc);
1950 if (init != orig_init)
1951 vds->var()->var_value()->set_init(init);
1953 return TRAVERSE_CONTINUE;
1956 // Implement the order of evaluation rules for the initializer of a
1960 Order_eval::variable(Named_object* no)
1962 if (no->is_result_variable())
1963 return TRAVERSE_CONTINUE;
1964 Variable* var = no->var_value();
1965 Expression* init = var->init();
1966 if (!var->is_global() || init == NULL)
1967 return TRAVERSE_CONTINUE;
1969 Find_eval_ordering find_eval_ordering;
1970 init->traverse_subexpressions(&find_eval_ordering);
1972 if (find_eval_ordering.size() <= 1)
1974 // If there is only one expression with a side-effect, we can
1975 // leave it in place.
1976 return TRAVERSE_SKIP_COMPONENTS;
1979 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1980 p != find_eval_ordering.end();
1983 Expression** pexpr = *p;
1984 source_location loc = (*pexpr)->location();
1985 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1986 var->add_preinit_statement(this->gogo_, ts);
1987 *pexpr = Expression::make_temporary_reference(ts, loc);
1990 return TRAVERSE_SKIP_COMPONENTS;
1993 // Use temporary variables to implement the order of evaluation rules.
1996 Gogo::order_evaluations()
1998 Order_eval order_eval(this);
1999 this->traverse(&order_eval);
2002 // Traversal to convert calls to the predeclared recover function to
2003 // pass in an argument indicating whether it can recover from a panic
2006 class Convert_recover : public Traverse
2009 Convert_recover(Named_object* arg)
2010 : Traverse(traverse_expressions),
2016 expression(Expression**);
2019 // The argument to pass to the function.
2023 // Convert calls to recover.
2026 Convert_recover::expression(Expression** pp)
2028 Call_expression* ce = (*pp)->call_expression();
2029 if (ce != NULL && ce->is_recover_call())
2030 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2032 return TRAVERSE_CONTINUE;
2035 // Traversal for build_recover_thunks.
2037 class Build_recover_thunks : public Traverse
2040 Build_recover_thunks(Gogo* gogo)
2041 : Traverse(traverse_functions),
2046 function(Named_object*);
2050 can_recover_arg(source_location);
2056 // If this function calls recover, turn it into a thunk.
2059 Build_recover_thunks::function(Named_object* orig_no)
2061 Function* orig_func = orig_no->func_value();
2062 if (!orig_func->calls_recover()
2063 || orig_func->is_recover_thunk()
2064 || orig_func->has_recover_thunk())
2065 return TRAVERSE_CONTINUE;
2067 Gogo* gogo = this->gogo_;
2068 source_location location = orig_func->location();
2073 Function_type* orig_fntype = orig_func->type();
2074 Typed_identifier_list* new_params = new Typed_identifier_list();
2075 std::string receiver_name;
2076 if (orig_fntype->is_method())
2078 const Typed_identifier* receiver = orig_fntype->receiver();
2079 snprintf(buf, sizeof buf, "rt.%u", count);
2081 receiver_name = buf;
2082 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2083 receiver->location()));
2085 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2086 if (orig_params != NULL && !orig_params->empty())
2088 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2089 p != orig_params->end();
2092 snprintf(buf, sizeof buf, "pt.%u", count);
2094 new_params->push_back(Typed_identifier(buf, p->type(),
2098 snprintf(buf, sizeof buf, "pr.%u", count);
2100 std::string can_recover_name = buf;
2101 new_params->push_back(Typed_identifier(can_recover_name,
2102 Type::lookup_bool_type(),
2103 orig_fntype->location()));
2105 const Typed_identifier_list* orig_results = orig_fntype->results();
2106 Typed_identifier_list* new_results;
2107 if (orig_results == NULL || orig_results->empty())
2111 new_results = new Typed_identifier_list();
2112 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2113 p != orig_results->end();
2115 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2118 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2120 orig_fntype->location());
2121 if (orig_fntype->is_varargs())
2122 new_fntype->set_is_varargs();
2124 std::string name = orig_no->name() + "$recover";
2125 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2127 Function *new_func = new_no->func_value();
2128 if (orig_func->enclosing() != NULL)
2129 new_func->set_enclosing(orig_func->enclosing());
2131 // We build the code for the original function attached to the new
2132 // function, and then swap the original and new function bodies.
2133 // This means that existing references to the original function will
2134 // then refer to the new function. That makes this code a little
2135 // confusing, in that the reference to NEW_NO really refers to the
2136 // other function, not the one we are building.
2138 Expression* closure = NULL;
2139 if (orig_func->needs_closure())
2141 Named_object* orig_closure_no = orig_func->closure_var();
2142 Variable* orig_closure_var = orig_closure_no->var_value();
2143 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2144 true, false, location);
2145 snprintf(buf, sizeof buf, "closure.%u", count);
2147 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2149 new_func->set_closure_var(new_closure_no);
2150 closure = Expression::make_var_reference(new_closure_no, location);
2153 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2155 Expression_list* args = new Expression_list();
2156 if (new_params != NULL)
2158 // Note that we skip the last parameter, which is the boolean
2159 // indicating whether recover can succed.
2160 for (Typed_identifier_list::const_iterator p = new_params->begin();
2161 p + 1 != new_params->end();
2164 Named_object* p_no = gogo->lookup(p->name(), NULL);
2165 gcc_assert(p_no != NULL
2166 && p_no->is_variable()
2167 && p_no->var_value()->is_parameter());
2168 args->push_back(Expression::make_var_reference(p_no, location));
2171 args->push_back(this->can_recover_arg(location));
2173 Call_expression* call = Expression::make_call(fn, args, false, location);
2176 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2177 s = Statement::make_statement(call);
2180 Expression_list* vals = new Expression_list();
2181 size_t rc = orig_fntype->results()->size();
2183 vals->push_back(call);
2186 for (size_t i = 0; i < rc; ++i)
2187 vals->push_back(Expression::make_call_result(call, i));
2189 s = Statement::make_return_statement(new_func->type()->results(),
2192 s->determine_types();
2193 gogo->add_statement(s);
2195 gogo->finish_function(location);
2197 // Swap the function bodies and types.
2198 new_func->swap_for_recover(orig_func);
2199 orig_func->set_is_recover_thunk();
2200 new_func->set_calls_recover();
2201 new_func->set_has_recover_thunk();
2203 Bindings* orig_bindings = orig_func->block()->bindings();
2204 Bindings* new_bindings = new_func->block()->bindings();
2205 if (orig_fntype->is_method())
2207 // We changed the receiver to be a regular parameter. We have
2208 // to update the binding accordingly in both functions.
2209 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2210 gcc_assert(orig_rec_no != NULL
2211 && orig_rec_no->is_variable()
2212 && !orig_rec_no->var_value()->is_receiver());
2213 orig_rec_no->var_value()->set_is_receiver();
2215 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2216 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2217 if (new_rec_no == NULL)
2218 gcc_assert(saw_errors());
2221 gcc_assert(new_rec_no->is_variable()
2222 && new_rec_no->var_value()->is_receiver());
2223 new_rec_no->var_value()->set_is_not_receiver();
2227 // Because we flipped blocks but not types, the can_recover
2228 // parameter appears in the (now) old bindings as a parameter.
2229 // Change it to a local variable, whereupon it will be discarded.
2230 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2231 gcc_assert(can_recover_no != NULL
2232 && can_recover_no->is_variable()
2233 && can_recover_no->var_value()->is_parameter());
2234 orig_bindings->remove_binding(can_recover_no);
2236 // Add the can_recover argument to the (now) new bindings, and
2237 // attach it to any recover statements.
2238 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2239 false, true, false, location);
2240 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2242 Convert_recover convert_recover(can_recover_no);
2243 new_func->traverse(&convert_recover);
2245 // Update the function pointers in any named results.
2246 new_func->update_named_result_variables();
2247 orig_func->update_named_result_variables();
2249 return TRAVERSE_CONTINUE;
2252 // Return the expression to pass for the .can_recover parameter to the
2253 // new function. This indicates whether a call to recover may return
2254 // non-nil. The expression is
2255 // __go_can_recover(__builtin_return_address()).
2258 Build_recover_thunks::can_recover_arg(source_location location)
2260 static Named_object* builtin_return_address;
2261 if (builtin_return_address == NULL)
2263 const source_location bloc = BUILTINS_LOCATION;
2265 Typed_identifier_list* param_types = new Typed_identifier_list();
2266 Type* uint_type = Type::lookup_integer_type("uint");
2267 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2269 Typed_identifier_list* return_types = new Typed_identifier_list();
2270 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2271 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2273 Function_type* fntype = Type::make_function_type(NULL, param_types,
2274 return_types, bloc);
2275 builtin_return_address =
2276 Named_object::make_function_declaration("__builtin_return_address",
2277 NULL, fntype, bloc);
2278 const char* n = "__builtin_return_address";
2279 builtin_return_address->func_declaration_value()->set_asm_name(n);
2282 static Named_object* can_recover;
2283 if (can_recover == NULL)
2285 const source_location bloc = BUILTINS_LOCATION;
2286 Typed_identifier_list* param_types = new Typed_identifier_list();
2287 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2288 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2289 Type* boolean_type = Type::lookup_bool_type();
2290 Typed_identifier_list* results = new Typed_identifier_list();
2291 results->push_back(Typed_identifier("", boolean_type, bloc));
2292 Function_type* fntype = Type::make_function_type(NULL, param_types,
2294 can_recover = Named_object::make_function_declaration("__go_can_recover",
2297 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2300 Expression* fn = Expression::make_func_reference(builtin_return_address,
2304 mpz_init_set_ui(zval, 0UL);
2305 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2307 Expression_list *args = new Expression_list();
2308 args->push_back(zexpr);
2310 Expression* call = Expression::make_call(fn, args, false, location);
2312 args = new Expression_list();
2313 args->push_back(call);
2315 fn = Expression::make_func_reference(can_recover, NULL, location);
2316 return Expression::make_call(fn, args, false, location);
2319 // Build thunks for functions which call recover. We build a new
2320 // function with an extra parameter, which is whether a call to
2321 // recover can succeed. We then move the body of this function to
2322 // that one. We then turn this function into a thunk which calls the
2323 // new one, passing the value of
2324 // __go_can_recover(__builtin_return_address()). The function will be
2325 // marked as not splitting the stack. This will cooperate with the
2326 // implementation of defer to make recover do the right thing.
2329 Gogo::build_recover_thunks()
2331 Build_recover_thunks build_recover_thunks(this);
2332 this->traverse(&build_recover_thunks);
2335 // Look for named types to see whether we need to create an interface
2338 class Build_method_tables : public Traverse
2341 Build_method_tables(Gogo* gogo,
2342 const std::vector<Interface_type*>& interfaces)
2343 : Traverse(traverse_types),
2344 gogo_(gogo), interfaces_(interfaces)
2353 // A list of locally defined interfaces which have hidden methods.
2354 const std::vector<Interface_type*>& interfaces_;
2357 // Build all required interface method tables for types. We need to
2358 // ensure that we have an interface method table for every interface
2359 // which has a hidden method, for every named type which implements
2360 // that interface. Normally we can just build interface method tables
2361 // as we need them. However, in some cases we can require an
2362 // interface method table for an interface defined in a different
2363 // package for a type defined in that package. If that interface and
2364 // type both use a hidden method, that is OK. However, we will not be
2365 // able to build that interface method table when we need it, because
2366 // the type's hidden method will be static. So we have to build it
2367 // here, and just refer it from other packages as needed.
2370 Gogo::build_interface_method_tables()
2372 std::vector<Interface_type*> hidden_interfaces;
2373 hidden_interfaces.reserve(this->interface_types_.size());
2374 for (std::vector<Interface_type*>::const_iterator pi =
2375 this->interface_types_.begin();
2376 pi != this->interface_types_.end();
2379 const Typed_identifier_list* methods = (*pi)->methods();
2380 if (methods == NULL)
2382 for (Typed_identifier_list::const_iterator pm = methods->begin();
2383 pm != methods->end();
2386 if (Gogo::is_hidden_name(pm->name()))
2388 hidden_interfaces.push_back(*pi);
2394 if (!hidden_interfaces.empty())
2396 // Now traverse the tree looking for all named types.
2397 Build_method_tables bmt(this, hidden_interfaces);
2398 this->traverse(&bmt);
2401 // We no longer need the list of interfaces.
2403 this->interface_types_.clear();
2406 // This is called for each type. For a named type, for each of the
2407 // interfaces with hidden methods that it implements, create the
2411 Build_method_tables::type(Type* type)
2413 Named_type* nt = type->named_type();
2416 for (std::vector<Interface_type*>::const_iterator p =
2417 this->interfaces_.begin();
2418 p != this->interfaces_.end();
2421 // We ask whether a pointer to the named type implements the
2422 // interface, because a pointer can implement more methods
2424 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2426 nt->interface_method_table(this->gogo_, *p, false);
2427 nt->interface_method_table(this->gogo_, *p, true);
2431 return TRAVERSE_CONTINUE;
2434 // Traversal class used to check for return statements.
2436 class Check_return_statements_traverse : public Traverse
2439 Check_return_statements_traverse()
2440 : Traverse(traverse_functions)
2444 function(Named_object*);
2447 // Check that a function has a return statement if it needs one.
2450 Check_return_statements_traverse::function(Named_object* no)
2452 Function* func = no->func_value();
2453 const Function_type* fntype = func->type();
2454 const Typed_identifier_list* results = fntype->results();
2456 // We only need a return statement if there is a return value.
2457 if (results == NULL || results->empty())
2458 return TRAVERSE_CONTINUE;
2460 if (func->block()->may_fall_through())
2461 error_at(func->location(), "control reaches end of non-void function");
2463 return TRAVERSE_CONTINUE;
2466 // Check return statements.
2469 Gogo::check_return_statements()
2471 Check_return_statements_traverse traverse;
2472 this->traverse(&traverse);
2475 // Get the unique prefix to use before all exported symbols. This
2476 // must be unique across the entire link.
2479 Gogo::unique_prefix() const
2481 gcc_assert(!this->unique_prefix_.empty());
2482 return this->unique_prefix_;
2485 // Set the unique prefix to use before all exported symbols. This
2486 // comes from the command line option -fgo-prefix=XXX.
2489 Gogo::set_unique_prefix(const std::string& arg)
2491 gcc_assert(this->unique_prefix_.empty());
2492 this->unique_prefix_ = arg;
2493 this->unique_prefix_specified_ = true;
2496 // Work out the package priority. It is one more than the maximum
2497 // priority of an imported package.
2500 Gogo::package_priority() const
2503 for (Packages::const_iterator p = this->packages_.begin();
2504 p != this->packages_.end();
2506 if (p->second->priority() > priority)
2507 priority = p->second->priority();
2508 return priority + 1;
2511 // Export identifiers as requested.
2516 // For now we always stream to a section. Later we may want to
2517 // support streaming to a separate file.
2518 Stream_to_section stream;
2520 Export exp(&stream);
2521 exp.register_builtin_types(this);
2522 exp.export_globals(this->package_name(),
2523 this->unique_prefix(),
2524 this->package_priority(),
2525 (this->need_init_fn_ && !this->is_main_package()
2526 ? this->get_init_fn_name()
2528 this->imported_init_fns_,
2529 this->package_->bindings());
2532 // Find the blocks in order to convert named types defined in blocks.
2534 class Convert_named_types : public Traverse
2537 Convert_named_types(Gogo* gogo)
2538 : Traverse(traverse_blocks),
2544 block(Block* block);
2551 Convert_named_types::block(Block* block)
2553 this->gogo_->convert_named_types_in_bindings(block->bindings());
2554 return TRAVERSE_CONTINUE;
2557 // Convert all named types to the backend representation. Since named
2558 // types can refer to other types, this needs to be done in the right
2559 // sequence, which is handled by Named_type::convert. Here we arrange
2560 // to call that for each named type.
2563 Gogo::convert_named_types()
2565 this->convert_named_types_in_bindings(this->globals_);
2566 for (Packages::iterator p = this->packages_.begin();
2567 p != this->packages_.end();
2570 Package* package = p->second;
2571 this->convert_named_types_in_bindings(package->bindings());
2574 Convert_named_types cnt(this);
2575 this->traverse(&cnt);
2577 // Make all the builtin named types used for type descriptors, and
2578 // then convert them. They will only be written out if they are
2580 Type::make_type_descriptor_type();
2581 Type::make_type_descriptor_ptr_type();
2582 Function_type::make_function_type_descriptor_type();
2583 Pointer_type::make_pointer_type_descriptor_type();
2584 Struct_type::make_struct_type_descriptor_type();
2585 Array_type::make_array_type_descriptor_type();
2586 Array_type::make_slice_type_descriptor_type();
2587 Map_type::make_map_type_descriptor_type();
2588 Channel_type::make_chan_type_descriptor_type();
2589 Interface_type::make_interface_type_descriptor_type();
2590 Type::convert_builtin_named_types(this);
2592 this->named_types_are_converted_ = true;
2595 // Convert all names types in a set of bindings.
2598 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2600 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2601 p != bindings->end_definitions();
2604 if ((*p)->is_type())
2605 (*p)->type_value()->convert(this);
2611 Function::Function(Function_type* type, Function* enclosing, Block* block,
2612 source_location location)
2613 : type_(type), enclosing_(enclosing), named_results_(NULL),
2614 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2615 defer_stack_(NULL), calls_recover_(false), is_recover_thunk_(false),
2616 has_recover_thunk_(false)
2620 // Create the named result variables.
2623 Function::create_named_result_variables(Gogo* gogo)
2625 const Typed_identifier_list* results = this->type_->results();
2628 || results->front().name().empty())
2631 this->named_results_ = new Named_results();
2632 this->named_results_->reserve(results->size());
2634 Block* block = this->block_;
2636 for (Typed_identifier_list::const_iterator p = results->begin();
2637 p != results->end();
2640 std::string name = p->name();
2641 if (Gogo::is_sink_name(name))
2643 static int unnamed_result_counter;
2645 snprintf(buf, sizeof buf, "_$%d", unnamed_result_counter);
2646 ++unnamed_result_counter;
2647 name = gogo->pack_hidden_name(buf, false);
2649 Result_variable* result = new Result_variable(p->type(), this, index);
2650 Named_object* no = block->bindings()->add_result_variable(name, result);
2651 if (no->is_result_variable())
2652 this->named_results_->push_back(no);
2656 // Update the named result variables when cloning a function which
2660 Function::update_named_result_variables()
2662 if (this->named_results_ == NULL)
2665 for (Named_results::iterator p = this->named_results_->begin();
2666 p != this->named_results_->end();
2668 (*p)->result_var_value()->set_function(this);
2671 // Return the closure variable, creating it if necessary.
2674 Function::closure_var()
2676 if (this->closure_var_ == NULL)
2678 // We don't know the type of the variable yet. We add fields as
2680 source_location loc = this->type_->location();
2681 Struct_field_list* sfl = new Struct_field_list;
2682 Type* struct_type = Type::make_struct_type(sfl, loc);
2683 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2684 NULL, false, true, false, loc);
2685 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2686 // Note that the new variable is not in any binding contour.
2688 return this->closure_var_;
2691 // Set the type of the closure variable.
2694 Function::set_closure_type()
2696 if (this->closure_var_ == NULL)
2698 Named_object* closure = this->closure_var_;
2699 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2700 unsigned int index = 0;
2701 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2702 p != this->closure_fields_.end();
2705 Named_object* no = p->first;
2707 snprintf(buf, sizeof buf, "%u", index);
2708 std::string n = no->name() + buf;
2710 if (no->is_variable())
2711 var_type = no->var_value()->type();
2713 var_type = no->result_var_value()->type();
2714 Type* field_type = Type::make_pointer_type(var_type);
2715 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2719 // Return whether this function is a method.
2722 Function::is_method() const
2724 return this->type_->is_method();
2727 // Add a label definition.
2730 Function::add_label_definition(const std::string& label_name,
2731 source_location location)
2733 Label* lnull = NULL;
2734 std::pair<Labels::iterator, bool> ins =
2735 this->labels_.insert(std::make_pair(label_name, lnull));
2738 // This is a new label.
2739 Label* label = new Label(label_name);
2740 label->define(location);
2741 ins.first->second = label;
2746 // The label was already in the hash table.
2747 Label* label = ins.first->second;
2748 if (!label->is_defined())
2750 label->define(location);
2755 error_at(location, "redefinition of label %qs",
2756 Gogo::message_name(label_name).c_str());
2757 inform(label->location(), "previous definition of %qs was here",
2758 Gogo::message_name(label_name).c_str());
2759 return new Label(label_name);
2764 // Add a reference to a label.
2767 Function::add_label_reference(const std::string& label_name)
2769 Label* lnull = NULL;
2770 std::pair<Labels::iterator, bool> ins =
2771 this->labels_.insert(std::make_pair(label_name, lnull));
2774 // The label was already in the hash table.
2775 return ins.first->second;
2779 gcc_assert(ins.first->second == NULL);
2780 Label* label = new Label(label_name);
2781 ins.first->second = label;
2786 // Swap one function with another. This is used when building the
2787 // thunk we use to call a function which calls recover. It may not
2788 // work for any other case.
2791 Function::swap_for_recover(Function *x)
2793 gcc_assert(this->enclosing_ == x->enclosing_);
2794 std::swap(this->named_results_, x->named_results_);
2795 std::swap(this->closure_var_, x->closure_var_);
2796 std::swap(this->block_, x->block_);
2797 gcc_assert(this->location_ == x->location_);
2798 gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2799 gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2802 // Traverse the tree.
2805 Function::traverse(Traverse* traverse)
2807 unsigned int traverse_mask = traverse->traverse_mask();
2810 & (Traverse::traverse_types | Traverse::traverse_expressions))
2813 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2814 return TRAVERSE_EXIT;
2817 // FIXME: We should check traverse_functions here if nested
2818 // functions are stored in block bindings.
2819 if (this->block_ != NULL
2821 & (Traverse::traverse_variables
2822 | Traverse::traverse_constants
2823 | Traverse::traverse_blocks
2824 | Traverse::traverse_statements
2825 | Traverse::traverse_expressions
2826 | Traverse::traverse_types)) != 0)
2828 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2829 return TRAVERSE_EXIT;
2832 return TRAVERSE_CONTINUE;
2835 // Work out types for unspecified variables and constants.
2838 Function::determine_types()
2840 if (this->block_ != NULL)
2841 this->block_->determine_types();
2844 // Export the function.
2847 Function::export_func(Export* exp, const std::string& name) const
2849 Function::export_func_with_type(exp, name, this->type_);
2852 // Export a function with a type.
2855 Function::export_func_with_type(Export* exp, const std::string& name,
2856 const Function_type* fntype)
2858 exp->write_c_string("func ");
2860 if (fntype->is_method())
2862 exp->write_c_string("(");
2863 exp->write_type(fntype->receiver()->type());
2864 exp->write_c_string(") ");
2867 exp->write_string(name);
2869 exp->write_c_string(" (");
2870 const Typed_identifier_list* parameters = fntype->parameters();
2871 if (parameters != NULL)
2873 bool is_varargs = fntype->is_varargs();
2875 for (Typed_identifier_list::const_iterator p = parameters->begin();
2876 p != parameters->end();
2882 exp->write_c_string(", ");
2883 if (!is_varargs || p + 1 != parameters->end())
2884 exp->write_type(p->type());
2887 exp->write_c_string("...");
2888 exp->write_type(p->type()->array_type()->element_type());
2892 exp->write_c_string(")");
2894 const Typed_identifier_list* results = fntype->results();
2895 if (results != NULL)
2897 if (results->size() == 1)
2899 exp->write_c_string(" ");
2900 exp->write_type(results->begin()->type());
2904 exp->write_c_string(" (");
2906 for (Typed_identifier_list::const_iterator p = results->begin();
2907 p != results->end();
2913 exp->write_c_string(", ");
2914 exp->write_type(p->type());
2916 exp->write_c_string(")");
2919 exp->write_c_string(";\n");
2922 // Import a function.
2925 Function::import_func(Import* imp, std::string* pname,
2926 Typed_identifier** preceiver,
2927 Typed_identifier_list** pparameters,
2928 Typed_identifier_list** presults,
2931 imp->require_c_string("func ");
2934 if (imp->peek_char() == '(')
2936 imp->require_c_string("(");
2937 Type* rtype = imp->read_type();
2938 *preceiver = new Typed_identifier(Import::import_marker, rtype,
2940 imp->require_c_string(") ");
2943 *pname = imp->read_identifier();
2945 Typed_identifier_list* parameters;
2946 *is_varargs = false;
2947 imp->require_c_string(" (");
2948 if (imp->peek_char() == ')')
2952 parameters = new Typed_identifier_list();
2955 if (imp->match_c_string("..."))
2961 Type* ptype = imp->read_type();
2963 ptype = Type::make_array_type(ptype, NULL);
2964 parameters->push_back(Typed_identifier(Import::import_marker,
2965 ptype, imp->location()));
2966 if (imp->peek_char() != ',')
2968 gcc_assert(!*is_varargs);
2969 imp->require_c_string(", ");
2972 imp->require_c_string(")");
2973 *pparameters = parameters;
2975 Typed_identifier_list* results;
2976 if (imp->peek_char() != ' ')
2980 results = new Typed_identifier_list();
2981 imp->require_c_string(" ");
2982 if (imp->peek_char() != '(')
2984 Type* rtype = imp->read_type();
2985 results->push_back(Typed_identifier(Import::import_marker, rtype,
2990 imp->require_c_string("(");
2993 Type* rtype = imp->read_type();
2994 results->push_back(Typed_identifier(Import::import_marker,
2995 rtype, imp->location()));
2996 if (imp->peek_char() != ',')
2998 imp->require_c_string(", ");
3000 imp->require_c_string(")");
3003 imp->require_c_string(";\n");
3004 *presults = results;
3009 Block::Block(Block* enclosing, source_location location)
3010 : enclosing_(enclosing), statements_(),
3011 bindings_(new Bindings(enclosing == NULL
3013 : enclosing->bindings())),
3014 start_location_(location),
3015 end_location_(UNKNOWN_LOCATION)
3019 // Add a statement to a block.
3022 Block::add_statement(Statement* statement)
3024 this->statements_.push_back(statement);
3027 // Add a statement to the front of a block. This is slow but is only
3028 // used for reference counts of parameters.
3031 Block::add_statement_at_front(Statement* statement)
3033 this->statements_.insert(this->statements_.begin(), statement);
3036 // Replace a statement in a block.
3039 Block::replace_statement(size_t index, Statement* s)
3041 gcc_assert(index < this->statements_.size());
3042 this->statements_[index] = s;
3045 // Add a statement before another statement.
3048 Block::insert_statement_before(size_t index, Statement* s)
3050 gcc_assert(index < this->statements_.size());
3051 this->statements_.insert(this->statements_.begin() + index, s);
3054 // Add a statement after another statement.
3057 Block::insert_statement_after(size_t index, Statement* s)
3059 gcc_assert(index < this->statements_.size());
3060 this->statements_.insert(this->statements_.begin() + index + 1, s);
3063 // Traverse the tree.
3066 Block::traverse(Traverse* traverse)
3068 unsigned int traverse_mask = traverse->traverse_mask();
3070 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3072 int t = traverse->block(this);
3073 if (t == TRAVERSE_EXIT)
3074 return TRAVERSE_EXIT;
3075 else if (t == TRAVERSE_SKIP_COMPONENTS)
3076 return TRAVERSE_CONTINUE;
3080 & (Traverse::traverse_variables
3081 | Traverse::traverse_constants
3082 | Traverse::traverse_expressions
3083 | Traverse::traverse_types)) != 0)
3085 for (Bindings::const_definitions_iterator pb =
3086 this->bindings_->begin_definitions();
3087 pb != this->bindings_->end_definitions();
3090 switch ((*pb)->classification())
3092 case Named_object::NAMED_OBJECT_CONST:
3093 if ((traverse_mask & Traverse::traverse_constants) != 0)
3095 if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
3096 return TRAVERSE_EXIT;
3098 if ((traverse_mask & Traverse::traverse_types) != 0
3099 || (traverse_mask & Traverse::traverse_expressions) != 0)
3101 Type* t = (*pb)->const_value()->type();
3103 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3104 return TRAVERSE_EXIT;
3106 if ((traverse_mask & Traverse::traverse_expressions) != 0
3107 || (traverse_mask & Traverse::traverse_types) != 0)
3109 if ((*pb)->const_value()->traverse_expression(traverse)
3111 return TRAVERSE_EXIT;
3115 case Named_object::NAMED_OBJECT_VAR:
3116 case Named_object::NAMED_OBJECT_RESULT_VAR:
3117 if ((traverse_mask & Traverse::traverse_variables) != 0)
3119 if (traverse->variable(*pb) == TRAVERSE_EXIT)
3120 return TRAVERSE_EXIT;
3122 if (((traverse_mask & Traverse::traverse_types) != 0
3123 || (traverse_mask & Traverse::traverse_expressions) != 0)
3124 && ((*pb)->is_result_variable()
3125 || (*pb)->var_value()->has_type()))
3127 Type* t = ((*pb)->is_variable()
3128 ? (*pb)->var_value()->type()
3129 : (*pb)->result_var_value()->type());
3131 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3132 return TRAVERSE_EXIT;
3134 if ((*pb)->is_variable()
3135 && ((traverse_mask & Traverse::traverse_expressions) != 0
3136 || (traverse_mask & Traverse::traverse_types) != 0))
3138 if ((*pb)->var_value()->traverse_expression(traverse)
3140 return TRAVERSE_EXIT;
3144 case Named_object::NAMED_OBJECT_FUNC:
3145 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3146 // FIXME: Where will nested functions be found?
3149 case Named_object::NAMED_OBJECT_TYPE:
3150 if ((traverse_mask & Traverse::traverse_types) != 0
3151 || (traverse_mask & Traverse::traverse_expressions) != 0)
3153 if (Type::traverse((*pb)->type_value(), traverse)
3155 return TRAVERSE_EXIT;
3159 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3160 case Named_object::NAMED_OBJECT_UNKNOWN:
3163 case Named_object::NAMED_OBJECT_PACKAGE:
3164 case Named_object::NAMED_OBJECT_SINK:
3173 // No point in checking traverse_mask here--if we got here we always
3174 // want to walk the statements. The traversal can insert new
3175 // statements before or after the current statement. Inserting
3176 // statements before the current statement requires updating I via
3177 // the pointer; those statements will not be traversed. Any new
3178 // statements inserted after the current statement will be traversed
3180 for (size_t i = 0; i < this->statements_.size(); ++i)
3182 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3183 return TRAVERSE_EXIT;
3186 return TRAVERSE_CONTINUE;
3189 // Work out types for unspecified variables and constants.
3192 Block::determine_types()
3194 for (Bindings::const_definitions_iterator pb =
3195 this->bindings_->begin_definitions();
3196 pb != this->bindings_->end_definitions();
3199 if ((*pb)->is_variable())
3200 (*pb)->var_value()->determine_type();
3201 else if ((*pb)->is_const())
3202 (*pb)->const_value()->determine_type();
3205 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3206 ps != this->statements_.end();
3208 (*ps)->determine_types();
3211 // Return true if the statements in this block may fall through.
3214 Block::may_fall_through() const
3216 if (this->statements_.empty())
3218 return this->statements_.back()->may_fall_through();
3223 Variable::Variable(Type* type, Expression* init, bool is_global,
3224 bool is_parameter, bool is_receiver,
3225 source_location location)
3226 : type_(type), init_(init), preinit_(NULL), location_(location),
3227 is_global_(is_global), is_parameter_(is_parameter),
3228 is_receiver_(is_receiver), is_varargs_parameter_(false),
3229 is_address_taken_(false), seen_(false), init_is_lowered_(false),
3230 type_from_init_tuple_(false), type_from_range_index_(false),
3231 type_from_range_value_(false), type_from_chan_element_(false),
3232 is_type_switch_var_(false), determined_type_(false)
3234 gcc_assert(type != NULL || init != NULL);
3235 gcc_assert(!is_parameter || init == NULL);
3238 // Traverse the initializer expression.
3241 Variable::traverse_expression(Traverse* traverse)
3243 if (this->preinit_ != NULL)
3245 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3246 return TRAVERSE_EXIT;
3248 if (this->init_ != NULL)
3250 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3251 return TRAVERSE_EXIT;
3253 return TRAVERSE_CONTINUE;
3256 // Lower the initialization expression after parsing is complete.
3259 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3261 if (this->init_ != NULL && !this->init_is_lowered_)
3265 // We will give an error elsewhere, this is just to prevent
3266 // an infinite loop.
3271 gogo->lower_expression(function, &this->init_);
3273 this->seen_ = false;
3275 this->init_is_lowered_ = true;
3279 // Get the preinit block.
3282 Variable::preinit_block(Gogo* gogo)
3284 gcc_assert(this->is_global_);
3285 if (this->preinit_ == NULL)
3286 this->preinit_ = new Block(NULL, this->location());
3288 // If a global variable has a preinitialization statement, then we
3289 // need to have an initialization function.
3290 gogo->set_need_init_fn();
3292 return this->preinit_;
3295 // Add a statement to be run before the initialization expression.
3298 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3300 Block* b = this->preinit_block(gogo);
3301 b->add_statement(s);
3302 b->set_end_location(s->location());
3305 // In an assignment which sets a variable to a tuple of EXPR, return
3306 // the type of the first element of the tuple.
3309 Variable::type_from_tuple(Expression* expr, bool report_error) const
3311 if (expr->map_index_expression() != NULL)
3313 Map_type* mt = expr->map_index_expression()->get_map_type();
3315 return Type::make_error_type();
3316 return mt->val_type();
3318 else if (expr->receive_expression() != NULL)
3320 Expression* channel = expr->receive_expression()->channel();
3321 Type* channel_type = channel->type();
3322 if (channel_type->channel_type() == NULL)
3323 return Type::make_error_type();
3324 return channel_type->channel_type()->element_type();
3329 error_at(this->location(), "invalid tuple definition");
3330 return Type::make_error_type();
3334 // Given EXPR used in a range clause, return either the index type or
3335 // the value type of the range, depending upon GET_INDEX_TYPE.
3338 Variable::type_from_range(Expression* expr, bool get_index_type,
3339 bool report_error) const
3341 Type* t = expr->type();
3342 if (t->array_type() != NULL
3343 || (t->points_to() != NULL
3344 && t->points_to()->array_type() != NULL
3345 && !t->points_to()->is_open_array_type()))
3348 return Type::lookup_integer_type("int");
3350 return t->deref()->array_type()->element_type();
3352 else if (t->is_string_type())
3353 return Type::lookup_integer_type("int");
3354 else if (t->map_type() != NULL)
3357 return t->map_type()->key_type();
3359 return t->map_type()->val_type();
3361 else if (t->channel_type() != NULL)
3364 return t->channel_type()->element_type();
3368 error_at(this->location(),
3369 "invalid definition of value variable for channel range");
3370 return Type::make_error_type();
3376 error_at(this->location(), "invalid type for range clause");
3377 return Type::make_error_type();
3381 // EXPR should be a channel. Return the channel's element type.
3384 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3386 Type* t = expr->type();
3387 if (t->channel_type() != NULL)
3388 return t->channel_type()->element_type();
3392 error_at(this->location(), "expected channel");
3393 return Type::make_error_type();
3397 // Return the type of the Variable. This may be called before
3398 // Variable::determine_type is called, which means that we may need to
3399 // get the type from the initializer. FIXME: If we combine lowering
3400 // with type determination, then this should be unnecessary.
3405 // A variable in a type switch with a nil case will have the wrong
3406 // type here. This gets fixed up in determine_type, below.
3407 Type* type = this->type_;
3408 Expression* init = this->init_;
3409 if (this->is_type_switch_var_
3410 && this->type_->is_nil_constant_as_type())
3412 Type_guard_expression* tge = this->init_->type_guard_expression();
3413 gcc_assert(tge != NULL);
3420 if (this->type_ == NULL || !this->type_->is_error_type())
3422 error_at(this->location_, "variable initializer refers to itself");
3423 this->type_ = Type::make_error_type();
3432 else if (this->type_from_init_tuple_)
3433 type = this->type_from_tuple(init, false);
3434 else if (this->type_from_range_index_ || this->type_from_range_value_)
3435 type = this->type_from_range(init, this->type_from_range_index_, false);
3436 else if (this->type_from_chan_element_)
3437 type = this->type_from_chan_element(init, false);
3440 gcc_assert(init != NULL);
3441 type = init->type();
3442 gcc_assert(type != NULL);
3444 // Variables should not have abstract types.
3445 if (type->is_abstract())
3446 type = type->make_non_abstract_type();
3448 if (type->is_void_type())
3449 type = Type::make_error_type();
3452 this->seen_ = false;
3457 // Fetch the type from a const pointer, in which case it should have
3458 // been set already.
3461 Variable::type() const
3463 gcc_assert(this->type_ != NULL);
3467 // Set the type if necessary.
3470 Variable::determine_type()
3472 if (this->determined_type_)
3474 this->determined_type_ = true;
3476 if (this->preinit_ != NULL)
3477 this->preinit_->determine_types();
3479 // A variable in a type switch with a nil case will have the wrong
3480 // type here. It will have an initializer which is a type guard.
3481 // We want to initialize it to the value without the type guard, and
3482 // use the type of that value as well.
3483 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3485 Type_guard_expression* tge = this->init_->type_guard_expression();
3486 gcc_assert(tge != NULL);
3488 this->init_ = tge->expr();
3491 if (this->init_ == NULL)
3492 gcc_assert(this->type_ != NULL && !this->type_->is_abstract());
3493 else if (this->type_from_init_tuple_)
3495 Expression *init = this->init_;
3496 init->determine_type_no_context();
3497 this->type_ = this->type_from_tuple(init, true);
3500 else if (this->type_from_range_index_ || this->type_from_range_value_)
3502 Expression* init = this->init_;
3503 init->determine_type_no_context();
3504 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3510 // type_from_chan_element_ should have been cleared during
3512 gcc_assert(!this->type_from_chan_element_);
3514 Type_context context(this->type_, false);
3515 this->init_->determine_type(&context);
3516 if (this->type_ == NULL)
3518 Type* type = this->init_->type();
3519 gcc_assert(type != NULL);
3520 if (type->is_abstract())
3521 type = type->make_non_abstract_type();
3523 if (type->is_void_type())
3525 error_at(this->location_, "variable has no type");
3526 type = Type::make_error_type();
3528 else if (type->is_nil_type())
3530 error_at(this->location_, "variable defined to nil type");
3531 type = Type::make_error_type();
3533 else if (type->is_call_multiple_result_type())
3535 error_at(this->location_,
3536 "single variable set to multiple value function call");
3537 type = Type::make_error_type();
3545 // Export the variable
3548 Variable::export_var(Export* exp, const std::string& name) const
3550 gcc_assert(this->is_global_);
3551 exp->write_c_string("var ");
3552 exp->write_string(name);
3553 exp->write_c_string(" ");
3554 exp->write_type(this->type());
3555 exp->write_c_string(";\n");
3558 // Import a variable.
3561 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3563 imp->require_c_string("var ");
3564 *pname = imp->read_identifier();
3565 imp->require_c_string(" ");
3566 *ptype = imp->read_type();
3567 imp->require_c_string(";\n");
3570 // Class Named_constant.
3572 // Traverse the initializer expression.
3575 Named_constant::traverse_expression(Traverse* traverse)
3577 return Expression::traverse(&this->expr_, traverse);
3580 // Determine the type of the constant.
3583 Named_constant::determine_type()
3585 if (this->type_ != NULL)
3587 Type_context context(this->type_, false);
3588 this->expr_->determine_type(&context);
3592 // A constant may have an abstract type.
3593 Type_context context(NULL, true);
3594 this->expr_->determine_type(&context);
3595 this->type_ = this->expr_->type();
3596 gcc_assert(this->type_ != NULL);
3600 // Indicate that we found and reported an error for this constant.
3603 Named_constant::set_error()
3605 this->type_ = Type::make_error_type();
3606 this->expr_ = Expression::make_error(this->location_);
3609 // Export a constant.
3612 Named_constant::export_const(Export* exp, const std::string& name) const
3614 exp->write_c_string("const ");
3615 exp->write_string(name);
3616 exp->write_c_string(" ");
3617 if (!this->type_->is_abstract())
3619 exp->write_type(this->type_);
3620 exp->write_c_string(" ");
3622 exp->write_c_string("= ");
3623 this->expr()->export_expression(exp);
3624 exp->write_c_string(";\n");
3627 // Import a constant.
3630 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3633 imp->require_c_string("const ");
3634 *pname = imp->read_identifier();
3635 imp->require_c_string(" ");
3636 if (imp->peek_char() == '=')
3640 *ptype = imp->read_type();
3641 imp->require_c_string(" ");
3643 imp->require_c_string("= ");
3644 *pexpr = Expression::import_expression(imp);
3645 imp->require_c_string(";\n");
3651 Type_declaration::add_method(const std::string& name, Function* function)
3653 Named_object* ret = Named_object::make_function(name, NULL, function);
3654 this->methods_.push_back(ret);
3658 // Add a method declaration.
3661 Type_declaration::add_method_declaration(const std::string& name,
3662 Function_type* type,
3663 source_location location)
3665 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3667 this->methods_.push_back(ret);
3671 // Return whether any methods ere defined.
3674 Type_declaration::has_methods() const
3676 return !this->methods_.empty();
3679 // Define methods for the real type.
3682 Type_declaration::define_methods(Named_type* nt)
3684 for (Methods::const_iterator p = this->methods_.begin();
3685 p != this->methods_.end();
3687 nt->add_existing_method(*p);
3690 // We are using the type. Return true if we should issue a warning.
3693 Type_declaration::using_type()
3695 bool ret = !this->issued_warning_;
3696 this->issued_warning_ = true;
3700 // Class Unknown_name.
3702 // Set the real named object.
3705 Unknown_name::set_real_named_object(Named_object* no)
3707 gcc_assert(this->real_named_object_ == NULL);
3708 gcc_assert(!no->is_unknown());
3709 this->real_named_object_ = no;
3712 // Class Named_object.
3714 Named_object::Named_object(const std::string& name,
3715 const Package* package,
3716 Classification classification)
3717 : name_(name), package_(package), classification_(classification),
3720 if (Gogo::is_sink_name(name))
3721 gcc_assert(classification == NAMED_OBJECT_SINK);
3724 // Make an unknown name. This is used by the parser. The name must
3725 // be resolved later. Unknown names are only added in the current
3729 Named_object::make_unknown_name(const std::string& name,
3730 source_location location)
3732 Named_object* named_object = new Named_object(name, NULL,
3733 NAMED_OBJECT_UNKNOWN);
3734 Unknown_name* value = new Unknown_name(location);
3735 named_object->u_.unknown_value = value;
3736 return named_object;
3742 Named_object::make_constant(const Typed_identifier& tid,
3743 const Package* package, Expression* expr,
3746 Named_object* named_object = new Named_object(tid.name(), package,
3747 NAMED_OBJECT_CONST);
3748 Named_constant* named_constant = new Named_constant(tid.type(), expr,
3751 named_object->u_.const_value = named_constant;
3752 return named_object;
3755 // Make a named type.
3758 Named_object::make_type(const std::string& name, const Package* package,
3759 Type* type, source_location location)
3761 Named_object* named_object = new Named_object(name, package,
3763 Named_type* named_type = Type::make_named_type(named_object, type, location);
3764 named_object->u_.type_value = named_type;
3765 return named_object;
3768 // Make a type declaration.
3771 Named_object::make_type_declaration(const std::string& name,
3772 const Package* package,
3773 source_location location)
3775 Named_object* named_object = new Named_object(name, package,
3776 NAMED_OBJECT_TYPE_DECLARATION);
3777 Type_declaration* type_declaration = new Type_declaration(location);
3778 named_object->u_.type_declaration = type_declaration;
3779 return named_object;
3785 Named_object::make_variable(const std::string& name, const Package* package,
3788 Named_object* named_object = new Named_object(name, package,
3790 named_object->u_.var_value = variable;
3791 return named_object;
3794 // Make a result variable.
3797 Named_object::make_result_variable(const std::string& name,
3798 Result_variable* result)
3800 Named_object* named_object = new Named_object(name, NULL,
3801 NAMED_OBJECT_RESULT_VAR);
3802 named_object->u_.result_var_value = result;
3803 return named_object;
3806 // Make a sink. This is used for the special blank identifier _.
3809 Named_object::make_sink()
3811 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
3814 // Make a named function.
3817 Named_object::make_function(const std::string& name, const Package* package,
3820 Named_object* named_object = new Named_object(name, package,
3822 named_object->u_.func_value = function;
3823 return named_object;
3826 // Make a function declaration.
3829 Named_object::make_function_declaration(const std::string& name,
3830 const Package* package,
3831 Function_type* fntype,
3832 source_location location)
3834 Named_object* named_object = new Named_object(name, package,
3835 NAMED_OBJECT_FUNC_DECLARATION);
3836 Function_declaration *func_decl = new Function_declaration(fntype, location);
3837 named_object->u_.func_declaration_value = func_decl;
3838 return named_object;
3844 Named_object::make_package(const std::string& alias, Package* package)
3846 Named_object* named_object = new Named_object(alias, NULL,
3847 NAMED_OBJECT_PACKAGE);
3848 named_object->u_.package_value = package;
3849 return named_object;
3852 // Return the name to use in an error message.
3855 Named_object::message_name() const
3857 if (this->package_ == NULL)
3858 return Gogo::message_name(this->name_);
3859 std::string ret = Gogo::message_name(this->package_->name());
3861 ret += Gogo::message_name(this->name_);
3865 // Set the type when a declaration is defined.
3868 Named_object::set_type_value(Named_type* named_type)
3870 gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
3871 Type_declaration* td = this->u_.type_declaration;
3872 td->define_methods(named_type);
3873 Named_object* in_function = td->in_function();
3874 if (in_function != NULL)
3875 named_type->set_in_function(in_function);
3877 this->classification_ = NAMED_OBJECT_TYPE;
3878 this->u_.type_value = named_type;
3881 // Define a function which was previously declared.
3884 Named_object::set_function_value(Function* function)
3886 gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
3887 this->classification_ = NAMED_OBJECT_FUNC;
3888 // FIXME: We should free the old value.
3889 this->u_.func_value = function;
3892 // Declare an unknown object as a type declaration.
3895 Named_object::declare_as_type()
3897 gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
3898 Unknown_name* unk = this->u_.unknown_value;
3899 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
3900 this->u_.type_declaration = new Type_declaration(unk->location());
3904 // Return the location of a named object.
3907 Named_object::location() const
3909 switch (this->classification_)
3912 case NAMED_OBJECT_UNINITIALIZED:
3915 case NAMED_OBJECT_UNKNOWN:
3916 return this->unknown_value()->location();
3918 case NAMED_OBJECT_CONST:
3919 return this->const_value()->location();
3921 case NAMED_OBJECT_TYPE:
3922 return this->type_value()->location();
3924 case NAMED_OBJECT_TYPE_DECLARATION:
3925 return this->type_declaration_value()->location();
3927 case NAMED_OBJECT_VAR:
3928 return this->var_value()->location();
3930 case NAMED_OBJECT_RESULT_VAR:
3931 return this->result_var_value()->function()->location();
3933 case NAMED_OBJECT_SINK:
3936 case NAMED_OBJECT_FUNC:
3937 return this->func_value()->location();
3939 case NAMED_OBJECT_FUNC_DECLARATION:
3940 return this->func_declaration_value()->location();
3942 case NAMED_OBJECT_PACKAGE:
3943 return this->package_value()->location();
3947 // Export a named object.
3950 Named_object::export_named_object(Export* exp) const
3952 switch (this->classification_)
3955 case NAMED_OBJECT_UNINITIALIZED:
3956 case NAMED_OBJECT_UNKNOWN:
3959 case NAMED_OBJECT_CONST:
3960 this->const_value()->export_const(exp, this->name_);
3963 case NAMED_OBJECT_TYPE:
3964 this->type_value()->export_named_type(exp, this->name_);
3967 case NAMED_OBJECT_TYPE_DECLARATION:
3968 error_at(this->type_declaration_value()->location(),
3969 "attempt to export %<%s%> which was declared but not defined",
3970 this->message_name().c_str());
3973 case NAMED_OBJECT_FUNC_DECLARATION:
3974 this->func_declaration_value()->export_func(exp, this->name_);
3977 case NAMED_OBJECT_VAR:
3978 this->var_value()->export_var(exp, this->name_);
3981 case NAMED_OBJECT_RESULT_VAR:
3982 case NAMED_OBJECT_SINK:
3985 case NAMED_OBJECT_FUNC:
3986 this->func_value()->export_func(exp, this->name_);
3993 Bindings::Bindings(Bindings* enclosing)
3994 : enclosing_(enclosing), named_objects_(), bindings_()
4001 Bindings::clear_file_scope()
4003 Contour::iterator p = this->bindings_.begin();
4004 while (p != this->bindings_.end())
4007 if (p->second->package() != NULL)
4009 else if (p->second->is_package())
4011 else if (p->second->is_function()
4012 && !p->second->func_value()->type()->is_method()
4013 && Gogo::unpack_hidden_name(p->second->name()) == "init")
4021 p = this->bindings_.erase(p);
4025 // Look up a symbol.
4028 Bindings::lookup(const std::string& name) const
4030 Contour::const_iterator p = this->bindings_.find(name);
4031 if (p != this->bindings_.end())
4032 return p->second->resolve();
4033 else if (this->enclosing_ != NULL)
4034 return this->enclosing_->lookup(name);
4039 // Look up a symbol locally.
4042 Bindings::lookup_local(const std::string& name) const
4044 Contour::const_iterator p = this->bindings_.find(name);
4045 if (p == this->bindings_.end())
4050 // Remove an object from a set of bindings. This is used for a
4051 // special case in thunks for functions which call recover.
4054 Bindings::remove_binding(Named_object* no)
4056 Contour::iterator pb = this->bindings_.find(no->name());
4057 gcc_assert(pb != this->bindings_.end());
4058 this->bindings_.erase(pb);
4059 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4060 pn != this->named_objects_.end();
4065 this->named_objects_.erase(pn);
4072 // Add a method to the list of objects. This is not added to the
4073 // lookup table. This is so that we have a single list of objects
4074 // declared at the top level, which we walk through when it's time to
4075 // convert to trees.
4078 Bindings::add_method(Named_object* method)
4080 this->named_objects_.push_back(method);
4083 // Add a generic Named_object to a Contour.
4086 Bindings::add_named_object_to_contour(Contour* contour,
4087 Named_object* named_object)
4089 gcc_assert(named_object == named_object->resolve());
4090 const std::string& name(named_object->name());
4091 gcc_assert(!Gogo::is_sink_name(name));
4093 std::pair<Contour::iterator, bool> ins =
4094 contour->insert(std::make_pair(name, named_object));
4097 // The name was already there.
4098 if (named_object->package() != NULL
4099 && ins.first->second->package() == named_object->package()
4100 && (ins.first->second->classification()
4101 == named_object->classification()))
4103 // This is a second import of the same object.
4104 return ins.first->second;
4106 ins.first->second = this->new_definition(ins.first->second,
4108 return ins.first->second;
4112 // Don't push declarations on the list. We push them on when
4113 // and if we find the definitions. That way we genericize the
4114 // functions in order.
4115 if (!named_object->is_type_declaration()
4116 && !named_object->is_function_declaration()
4117 && !named_object->is_unknown())
4118 this->named_objects_.push_back(named_object);
4119 return named_object;
4123 // We had an existing named object OLD_OBJECT, and we've seen a new
4124 // one NEW_OBJECT with the same name. FIXME: This does not free the
4125 // new object when we don't need it.
4128 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4131 switch (old_object->classification())
4134 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4137 case Named_object::NAMED_OBJECT_UNKNOWN:
4139 Named_object* real = old_object->unknown_value()->real_named_object();
4141 return this->new_definition(real, new_object);
4142 gcc_assert(!new_object->is_unknown());
4143 old_object->unknown_value()->set_real_named_object(new_object);
4144 if (!new_object->is_type_declaration()
4145 && !new_object->is_function_declaration())
4146 this->named_objects_.push_back(new_object);
4150 case Named_object::NAMED_OBJECT_CONST:
4153 case Named_object::NAMED_OBJECT_TYPE:
4154 if (new_object->is_type_declaration())
4158 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4159 if (new_object->is_type_declaration())
4161 if (new_object->is_type())
4163 old_object->set_type_value(new_object->type_value());
4164 new_object->type_value()->set_named_object(old_object);
4165 this->named_objects_.push_back(old_object);
4170 case Named_object::NAMED_OBJECT_VAR:
4171 case Named_object::NAMED_OBJECT_RESULT_VAR:
4174 case Named_object::NAMED_OBJECT_SINK:
4177 case Named_object::NAMED_OBJECT_FUNC:
4178 if (new_object->is_function_declaration())
4180 if (!new_object->func_declaration_value()->asm_name().empty())
4181 sorry("__asm__ for function definitions");
4182 Function_type* old_type = old_object->func_value()->type();
4183 Function_type* new_type =
4184 new_object->func_declaration_value()->type();
4185 if (old_type->is_valid_redeclaration(new_type, &reason))
4190 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4192 Function_type* old_type = old_object->func_declaration_value()->type();
4193 if (new_object->is_function_declaration())
4195 Function_type* new_type =
4196 new_object->func_declaration_value()->type();
4197 if (old_type->is_valid_redeclaration(new_type, &reason))
4200 if (new_object->is_function())
4202 Function_type* new_type = new_object->func_value()->type();
4203 if (old_type->is_valid_redeclaration(new_type, &reason))
4205 if (!old_object->func_declaration_value()->asm_name().empty())
4206 sorry("__asm__ for function definitions");
4207 old_object->set_function_value(new_object->func_value());
4208 this->named_objects_.push_back(old_object);
4215 case Named_object::NAMED_OBJECT_PACKAGE:
4216 if (new_object->is_package()
4217 && (old_object->package_value()->name()
4218 == new_object->package_value()->name()))
4224 std::string n = old_object->message_name();
4226 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4228 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4231 inform(old_object->location(), "previous definition of %qs was here",
4237 // Add a named type.
4240 Bindings::add_named_type(Named_type* named_type)
4242 return this->add_named_object(named_type->named_object());
4248 Bindings::add_function(const std::string& name, const Package* package,
4251 return this->add_named_object(Named_object::make_function(name, package,
4255 // Add a function declaration.
4258 Bindings::add_function_declaration(const std::string& name,
4259 const Package* package,
4260 Function_type* type,
4261 source_location location)
4263 Named_object* no = Named_object::make_function_declaration(name, package,
4265 return this->add_named_object(no);
4268 // Define a type which was previously declared.
4271 Bindings::define_type(Named_object* no, Named_type* type)
4273 no->set_type_value(type);
4274 this->named_objects_.push_back(no);
4277 // Traverse bindings.
4280 Bindings::traverse(Traverse* traverse, bool is_global)
4282 unsigned int traverse_mask = traverse->traverse_mask();
4284 // We don't use an iterator because we permit the traversal to add
4285 // new global objects.
4286 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4288 Named_object* p = this->named_objects_[i];
4289 switch (p->classification())
4291 case Named_object::NAMED_OBJECT_CONST:
4292 if ((traverse_mask & Traverse::traverse_constants) != 0)
4294 if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4295 return TRAVERSE_EXIT;
4297 if ((traverse_mask & Traverse::traverse_types) != 0
4298 || (traverse_mask & Traverse::traverse_expressions) != 0)
4300 Type* t = p->const_value()->type();
4302 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4303 return TRAVERSE_EXIT;
4304 if (p->const_value()->traverse_expression(traverse)
4306 return TRAVERSE_EXIT;
4310 case Named_object::NAMED_OBJECT_VAR:
4311 case Named_object::NAMED_OBJECT_RESULT_VAR:
4312 if ((traverse_mask & Traverse::traverse_variables) != 0)
4314 if (traverse->variable(p) == TRAVERSE_EXIT)
4315 return TRAVERSE_EXIT;
4317 if (((traverse_mask & Traverse::traverse_types) != 0
4318 || (traverse_mask & Traverse::traverse_expressions) != 0)
4319 && (p->is_result_variable()
4320 || p->var_value()->has_type()))
4322 Type* t = (p->is_variable()
4323 ? p->var_value()->type()
4324 : p->result_var_value()->type());
4326 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4327 return TRAVERSE_EXIT;
4329 if (p->is_variable()
4330 && ((traverse_mask & Traverse::traverse_types) != 0
4331 || (traverse_mask & Traverse::traverse_expressions) != 0))
4333 if (p->var_value()->traverse_expression(traverse)
4335 return TRAVERSE_EXIT;
4339 case Named_object::NAMED_OBJECT_FUNC:
4340 if ((traverse_mask & Traverse::traverse_functions) != 0)
4342 int t = traverse->function(p);
4343 if (t == TRAVERSE_EXIT)
4344 return TRAVERSE_EXIT;
4345 else if (t == TRAVERSE_SKIP_COMPONENTS)
4350 & (Traverse::traverse_variables
4351 | Traverse::traverse_constants
4352 | Traverse::traverse_functions
4353 | Traverse::traverse_blocks
4354 | Traverse::traverse_statements
4355 | Traverse::traverse_expressions
4356 | Traverse::traverse_types)) != 0)
4358 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4359 return TRAVERSE_EXIT;
4363 case Named_object::NAMED_OBJECT_PACKAGE:
4364 // These are traversed in Gogo::traverse.
4365 gcc_assert(is_global);
4368 case Named_object::NAMED_OBJECT_TYPE:
4369 if ((traverse_mask & Traverse::traverse_types) != 0
4370 || (traverse_mask & Traverse::traverse_expressions) != 0)
4372 if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4373 return TRAVERSE_EXIT;
4377 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4378 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4379 case Named_object::NAMED_OBJECT_UNKNOWN:
4382 case Named_object::NAMED_OBJECT_SINK:
4388 return TRAVERSE_CONTINUE;
4393 Package::Package(const std::string& name, const std::string& unique_prefix,
4394 source_location location)
4395 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4396 priority_(0), location_(location), used_(false), is_imported_(false),
4397 uses_sink_alias_(false)
4399 gcc_assert(!name.empty() && !unique_prefix.empty());
4402 // Set the priority. We may see multiple priorities for an imported
4403 // package; we want to use the largest one.
4406 Package::set_priority(int priority)
4408 if (priority > this->priority_)
4409 this->priority_ = priority;
4412 // Determine types of constants. Everything else in a package
4413 // (variables, function declarations) should already have a fixed
4414 // type. Constants may have abstract types.
4417 Package::determine_types()
4419 Bindings* bindings = this->bindings_;
4420 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4421 p != bindings->end_definitions();
4424 if ((*p)->is_const())
4425 (*p)->const_value()->determine_type();
4433 Traverse::~Traverse()
4435 if (this->types_seen_ != NULL)
4436 delete this->types_seen_;
4437 if (this->expressions_seen_ != NULL)
4438 delete this->expressions_seen_;
4441 // Record that we are looking at a type, and return true if we have
4445 Traverse::remember_type(const Type* type)
4447 if (type->is_error_type())
4449 gcc_assert((this->traverse_mask() & traverse_types) != 0
4450 || (this->traverse_mask() & traverse_expressions) != 0);
4451 // We only have to remember named types, as they are the only ones
4452 // we can see multiple times in a traversal.
4453 if (type->classification() != Type::TYPE_NAMED)
4455 if (this->types_seen_ == NULL)
4456 this->types_seen_ = new Types_seen();
4457 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4461 // Record that we are looking at an expression, and return true if we
4462 // have already seen it.
4465 Traverse::remember_expression(const Expression* expression)
4467 gcc_assert((this->traverse_mask() & traverse_types) != 0
4468 || (this->traverse_mask() & traverse_expressions) != 0);
4469 if (this->expressions_seen_ == NULL)
4470 this->expressions_seen_ = new Expressions_seen();
4471 std::pair<Expressions_seen::iterator, bool> ins =
4472 this->expressions_seen_->insert(expression);
4476 // The default versions of these functions should never be called: the
4477 // traversal mask indicates which functions may be called.
4480 Traverse::variable(Named_object*)
4486 Traverse::constant(Named_object*, bool)
4492 Traverse::function(Named_object*)
4498 Traverse::block(Block*)
4504 Traverse::statement(Block*, size_t*, Statement*)
4510 Traverse::expression(Expression**)
4516 Traverse::type(Type*)