1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
13 #include "statements.h"
14 #include "expressions.h"
24 Gogo::Gogo(Backend* backend, int int_type_size, int pointer_size)
28 globals_(new Bindings(NULL)),
30 imported_unsafe_(false),
32 map_descriptors_(NULL),
33 type_descriptor_decls_(NULL),
39 unique_prefix_specified_(false),
41 named_types_are_converted_(false)
43 const source_location loc = BUILTINS_LOCATION;
45 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
46 RUNTIME_TYPE_KIND_UINT8);
47 this->add_named_type(uint8_type);
48 this->add_named_type(Type::make_integer_type("uint16", true, 16,
49 RUNTIME_TYPE_KIND_UINT16));
50 this->add_named_type(Type::make_integer_type("uint32", true, 32,
51 RUNTIME_TYPE_KIND_UINT32));
52 this->add_named_type(Type::make_integer_type("uint64", true, 64,
53 RUNTIME_TYPE_KIND_UINT64));
55 this->add_named_type(Type::make_integer_type("int8", false, 8,
56 RUNTIME_TYPE_KIND_INT8));
57 this->add_named_type(Type::make_integer_type("int16", false, 16,
58 RUNTIME_TYPE_KIND_INT16));
59 this->add_named_type(Type::make_integer_type("int32", false, 32,
60 RUNTIME_TYPE_KIND_INT32));
61 this->add_named_type(Type::make_integer_type("int64", false, 64,
62 RUNTIME_TYPE_KIND_INT64));
64 this->add_named_type(Type::make_float_type("float32", 32,
65 RUNTIME_TYPE_KIND_FLOAT32));
66 this->add_named_type(Type::make_float_type("float64", 64,
67 RUNTIME_TYPE_KIND_FLOAT64));
69 this->add_named_type(Type::make_complex_type("complex64", 64,
70 RUNTIME_TYPE_KIND_COMPLEX64));
71 this->add_named_type(Type::make_complex_type("complex128", 128,
72 RUNTIME_TYPE_KIND_COMPLEX128));
74 if (int_type_size < 32)
76 this->add_named_type(Type::make_integer_type("uint", true,
78 RUNTIME_TYPE_KIND_UINT));
79 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
80 RUNTIME_TYPE_KIND_INT);
81 this->add_named_type(int_type);
83 // "byte" is an alias for "uint8". Construct a Named_object which
84 // points to UINT8_TYPE. Note that this breaks the normal pairing
85 // in which a Named_object points to a Named_type which points back
86 // to the same Named_object.
87 Named_object* byte_type = this->declare_type("byte", loc);
88 byte_type->set_type_value(uint8_type);
90 this->add_named_type(Type::make_integer_type("uintptr", true,
92 RUNTIME_TYPE_KIND_UINTPTR));
94 this->add_named_type(Type::make_named_bool_type());
96 this->add_named_type(Type::make_named_string_type());
98 this->globals_->add_constant(Typed_identifier("true",
99 Type::make_boolean_type(),
102 Expression::make_boolean(true, loc),
104 this->globals_->add_constant(Typed_identifier("false",
105 Type::make_boolean_type(),
108 Expression::make_boolean(false, loc),
111 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
114 Expression::make_nil(loc),
117 Type* abstract_int_type = Type::make_abstract_integer_type();
118 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
121 Expression::make_iota(),
124 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
125 new_type->set_is_varargs();
126 new_type->set_is_builtin();
127 this->globals_->add_function_declaration("new", NULL, new_type, loc);
129 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
130 make_type->set_is_varargs();
131 make_type->set_is_builtin();
132 this->globals_->add_function_declaration("make", NULL, make_type, loc);
134 Typed_identifier_list* len_result = new Typed_identifier_list();
135 len_result->push_back(Typed_identifier("", int_type, loc));
136 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
138 len_type->set_is_builtin();
139 this->globals_->add_function_declaration("len", NULL, len_type, loc);
141 Typed_identifier_list* cap_result = new Typed_identifier_list();
142 cap_result->push_back(Typed_identifier("", int_type, loc));
143 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
145 cap_type->set_is_builtin();
146 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
148 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
149 print_type->set_is_varargs();
150 print_type->set_is_builtin();
151 this->globals_->add_function_declaration("print", NULL, print_type, loc);
153 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
154 print_type->set_is_varargs();
155 print_type->set_is_builtin();
156 this->globals_->add_function_declaration("println", NULL, print_type, loc);
158 Type *empty = Type::make_interface_type(NULL, loc);
159 Typed_identifier_list* panic_parms = new Typed_identifier_list();
160 panic_parms->push_back(Typed_identifier("e", empty, loc));
161 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
163 panic_type->set_is_builtin();
164 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
166 Typed_identifier_list* recover_result = new Typed_identifier_list();
167 recover_result->push_back(Typed_identifier("", empty, loc));
168 Function_type* recover_type = Type::make_function_type(NULL, NULL,
171 recover_type->set_is_builtin();
172 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
174 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
175 close_type->set_is_varargs();
176 close_type->set_is_builtin();
177 this->globals_->add_function_declaration("close", NULL, close_type, loc);
179 Typed_identifier_list* copy_result = new Typed_identifier_list();
180 copy_result->push_back(Typed_identifier("", int_type, loc));
181 Function_type* copy_type = Type::make_function_type(NULL, NULL,
183 copy_type->set_is_varargs();
184 copy_type->set_is_builtin();
185 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
187 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
188 append_type->set_is_varargs();
189 append_type->set_is_builtin();
190 this->globals_->add_function_declaration("append", NULL, append_type, loc);
192 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
193 complex_type->set_is_varargs();
194 complex_type->set_is_builtin();
195 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
197 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
198 real_type->set_is_varargs();
199 real_type->set_is_builtin();
200 this->globals_->add_function_declaration("real", NULL, real_type, loc);
202 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
203 imag_type->set_is_varargs();
204 imag_type->set_is_builtin();
205 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
207 this->define_builtin_function_trees();
210 // Munge name for use in an error message.
213 Gogo::message_name(const std::string& name)
215 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
218 // Get the package name.
221 Gogo::package_name() const
223 gcc_assert(this->package_ != NULL);
224 return this->package_->name();
227 // Set the package name.
230 Gogo::set_package_name(const std::string& package_name,
231 source_location location)
233 if (this->package_ != NULL && this->package_->name() != package_name)
235 error_at(location, "expected package %<%s%>",
236 Gogo::message_name(this->package_->name()).c_str());
240 // If the user did not specify a unique prefix, we always use "go".
241 // This in effect requires that the package name be unique.
242 if (this->unique_prefix_.empty())
243 this->unique_prefix_ = "go";
245 this->package_ = this->register_package(package_name, this->unique_prefix_,
248 // We used to permit people to qualify symbols with the current
249 // package name (e.g., P.x), but we no longer do.
250 // this->globals_->add_package(package_name, this->package_);
252 if (this->is_main_package())
254 // Declare "main" as a function which takes no parameters and
256 this->declare_function("main",
257 Type::make_function_type(NULL, NULL, NULL,
263 // Return whether this is the "main" package. This is not true if
264 // -fgo-prefix was used.
267 Gogo::is_main_package() const
269 return this->package_name() == "main" && !this->unique_prefix_specified_;
275 Gogo::import_package(const std::string& filename,
276 const std::string& local_name,
277 bool is_local_name_exported,
278 source_location location)
280 if (filename == "unsafe")
282 this->import_unsafe(local_name, is_local_name_exported, location);
286 Imports::const_iterator p = this->imports_.find(filename);
287 if (p != this->imports_.end())
289 Package* package = p->second;
290 package->set_location(location);
291 package->set_is_imported();
292 std::string ln = local_name;
293 bool is_ln_exported = is_local_name_exported;
296 ln = package->name();
297 is_ln_exported = Lex::is_exported_name(ln);
301 Bindings* bindings = package->bindings();
302 for (Bindings::const_declarations_iterator p =
303 bindings->begin_declarations();
304 p != bindings->end_declarations();
306 this->add_named_object(p->second);
309 package->set_uses_sink_alias();
312 ln = this->pack_hidden_name(ln, is_ln_exported);
313 this->package_->bindings()->add_package(ln, package);
318 Import::Stream* stream = Import::open_package(filename, location);
321 error_at(location, "import file %qs not found", filename.c_str());
325 Import imp(stream, location);
326 imp.register_builtin_types(this);
327 Package* package = imp.import(this, local_name, is_local_name_exported);
330 if (package->name() == this->package_name()
331 && package->unique_prefix() == this->unique_prefix())
333 ("imported package uses same package name and prefix "
334 "as package being compiled (see -fgo-prefix option)"));
336 this->imports_.insert(std::make_pair(filename, package));
337 package->set_is_imported();
343 // Add an import control function for an imported package to the list.
346 Gogo::add_import_init_fn(const std::string& package_name,
347 const std::string& init_name, int prio)
349 for (std::set<Import_init>::const_iterator p =
350 this->imported_init_fns_.begin();
351 p != this->imported_init_fns_.end();
354 if (p->init_name() == init_name
355 && (p->package_name() != package_name || p->priority() != prio))
357 error("duplicate package initialization name %qs",
358 Gogo::message_name(init_name).c_str());
359 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
360 Gogo::message_name(p->package_name()).c_str(),
362 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
363 Gogo::message_name(package_name).c_str(), prio);
368 this->imported_init_fns_.insert(Import_init(package_name, init_name,
372 // Return whether we are at the global binding level.
375 Gogo::in_global_scope() const
377 return this->functions_.empty();
380 // Return the current binding contour.
383 Gogo::current_bindings()
385 if (!this->functions_.empty())
386 return this->functions_.back().blocks.back()->bindings();
387 else if (this->package_ != NULL)
388 return this->package_->bindings();
390 return this->globals_;
394 Gogo::current_bindings() const
396 if (!this->functions_.empty())
397 return this->functions_.back().blocks.back()->bindings();
398 else if (this->package_ != NULL)
399 return this->package_->bindings();
401 return this->globals_;
404 // Return the current block.
407 Gogo::current_block()
409 if (this->functions_.empty())
412 return this->functions_.back().blocks.back();
415 // Look up a name in the current binding contour. If PFUNCTION is not
416 // NULL, set it to the function in which the name is defined, or NULL
417 // if the name is defined in global scope.
420 Gogo::lookup(const std::string& name, Named_object** pfunction) const
422 if (pfunction != NULL)
425 if (Gogo::is_sink_name(name))
426 return Named_object::make_sink();
428 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
429 p != this->functions_.rend();
432 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
435 if (pfunction != NULL)
436 *pfunction = p->function;
441 if (this->package_ != NULL)
443 Named_object* ret = this->package_->bindings()->lookup(name);
446 if (ret->package() != NULL)
447 ret->package()->set_used();
452 // We do not look in the global namespace. If we did, the global
453 // namespace would effectively hide names which were defined in
454 // package scope which we have not yet seen. Instead,
455 // define_global_names is called after parsing is over to connect
456 // undefined names at package scope with names defined at global
462 // Look up a name in the current block, without searching enclosing
466 Gogo::lookup_in_block(const std::string& name) const
468 gcc_assert(!this->functions_.empty());
469 gcc_assert(!this->functions_.back().blocks.empty());
470 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
473 // Look up a name in the global namespace.
476 Gogo::lookup_global(const char* name) const
478 return this->globals_->lookup(name);
481 // Add an imported package.
484 Gogo::add_imported_package(const std::string& real_name,
485 const std::string& alias_arg,
486 bool is_alias_exported,
487 const std::string& unique_prefix,
488 source_location location,
489 bool* padd_to_globals)
491 // FIXME: Now that we compile packages as a whole, should we permit
492 // importing the current package?
493 if (this->package_name() == real_name
494 && this->unique_prefix() == unique_prefix)
496 *padd_to_globals = false;
497 if (!alias_arg.empty() && alias_arg != ".")
499 std::string alias = this->pack_hidden_name(alias_arg,
501 this->package_->bindings()->add_package(alias, this->package_);
503 return this->package_;
505 else if (alias_arg == ".")
507 *padd_to_globals = true;
508 return this->register_package(real_name, unique_prefix, location);
510 else if (alias_arg == "_")
512 Package* ret = this->register_package(real_name, unique_prefix, location);
513 ret->set_uses_sink_alias();
518 *padd_to_globals = false;
519 std::string alias = alias_arg;
523 is_alias_exported = Lex::is_exported_name(alias);
525 alias = this->pack_hidden_name(alias, is_alias_exported);
526 Named_object* no = this->add_package(real_name, alias, unique_prefix,
528 if (!no->is_package())
530 return no->package_value();
537 Gogo::add_package(const std::string& real_name, const std::string& alias,
538 const std::string& unique_prefix, source_location location)
540 gcc_assert(this->in_global_scope());
542 // Register the package. Note that we might have already seen it in
543 // an earlier import.
544 Package* package = this->register_package(real_name, unique_prefix, location);
546 return this->package_->bindings()->add_package(alias, package);
549 // Register a package. This package may or may not be imported. This
550 // returns the Package structure for the package, creating if it
554 Gogo::register_package(const std::string& package_name,
555 const std::string& unique_prefix,
556 source_location location)
558 gcc_assert(!unique_prefix.empty() && !package_name.empty());
559 std::string name = unique_prefix + '.' + package_name;
560 Package* package = NULL;
561 std::pair<Packages::iterator, bool> ins =
562 this->packages_.insert(std::make_pair(name, package));
565 // We have seen this package name before.
566 package = ins.first->second;
567 gcc_assert(package != NULL);
568 gcc_assert(package->name() == package_name
569 && package->unique_prefix() == unique_prefix);
570 if (package->location() == UNKNOWN_LOCATION)
571 package->set_location(location);
575 // First time we have seen this package name.
576 package = new Package(package_name, unique_prefix, location);
577 gcc_assert(ins.first->second == NULL);
578 ins.first->second = package;
584 // Start compiling a function.
587 Gogo::start_function(const std::string& name, Function_type* type,
588 bool add_method_to_type, source_location location)
590 bool at_top_level = this->functions_.empty();
592 Block* block = new Block(NULL, location);
594 Function* enclosing = (at_top_level
596 : this->functions_.back().function->func_value());
598 Function* function = new Function(type, enclosing, block, location);
600 if (type->is_method())
602 const Typed_identifier* receiver = type->receiver();
603 Variable* this_param = new Variable(receiver->type(), NULL, false,
604 true, true, location);
605 std::string name = receiver->name();
608 // We need to give receivers a name since they wind up in
609 // DECL_ARGUMENTS. FIXME.
610 static unsigned int count;
612 snprintf(buf, sizeof buf, "r.%u", count);
616 block->bindings()->add_variable(name, NULL, this_param);
619 const Typed_identifier_list* parameters = type->parameters();
620 bool is_varargs = type->is_varargs();
621 if (parameters != NULL)
623 for (Typed_identifier_list::const_iterator p = parameters->begin();
624 p != parameters->end();
627 Variable* param = new Variable(p->type(), NULL, false, true, false,
629 if (is_varargs && p + 1 == parameters->end())
630 param->set_is_varargs_parameter();
632 std::string name = p->name();
633 if (name.empty() || Gogo::is_sink_name(name))
635 // We need to give parameters a name since they wind up
636 // in DECL_ARGUMENTS. FIXME.
637 static unsigned int count;
639 snprintf(buf, sizeof buf, "p.%u", count);
643 block->bindings()->add_variable(name, NULL, param);
647 function->create_result_variables(this);
649 const std::string* pname;
650 std::string nested_name;
651 bool is_init = false;
652 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
654 if ((type->parameters() != NULL && !type->parameters()->empty())
655 || (type->results() != NULL && !type->results()->empty()))
657 "func init must have no arguments and no return values");
658 // There can be multiple "init" functions, so give them each a
660 static int init_count;
662 snprintf(buf, sizeof buf, ".$init%d", init_count);
665 pname = &nested_name;
668 else if (!name.empty())
672 // Invent a name for a nested function.
673 static int nested_count;
675 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
678 pname = &nested_name;
682 if (Gogo::is_sink_name(*pname))
684 static int sink_count;
686 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
688 ret = Named_object::make_function(buf, NULL, function);
690 else if (!type->is_method())
692 ret = this->package_->bindings()->add_function(*pname, NULL, function);
693 if (!ret->is_function() || ret->func_value() != function)
695 // Redefinition error. Invent a name to avoid knockon
697 static int redefinition_count;
699 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
700 ++redefinition_count;
701 ret = this->package_->bindings()->add_function(buf, NULL, function);
706 if (!add_method_to_type)
707 ret = Named_object::make_function(name, NULL, function);
710 gcc_assert(at_top_level);
711 Type* rtype = type->receiver()->type();
713 // We want to look through the pointer created by the
714 // parser, without getting an error if the type is not yet
716 if (rtype->classification() == Type::TYPE_POINTER)
717 rtype = rtype->points_to();
719 if (rtype->is_error_type())
720 ret = Named_object::make_function(name, NULL, function);
721 else if (rtype->named_type() != NULL)
723 ret = rtype->named_type()->add_method(name, function);
724 if (!ret->is_function())
726 // Redefinition error.
727 ret = Named_object::make_function(name, NULL, function);
730 else if (rtype->forward_declaration_type() != NULL)
732 Named_object* type_no =
733 rtype->forward_declaration_type()->named_object();
734 if (type_no->is_unknown())
736 // If we are seeing methods it really must be a
737 // type. Declare it as such. An alternative would
738 // be to support lists of methods for unknown
739 // expressions. Either way the error messages if
740 // this is not a type are going to get confusing.
741 Named_object* declared =
742 this->declare_package_type(type_no->name(),
743 type_no->location());
745 == type_no->unknown_value()->real_named_object());
747 ret = rtype->forward_declaration_type()->add_method(name,
753 this->package_->bindings()->add_method(ret);
756 this->functions_.resize(this->functions_.size() + 1);
757 Open_function& of(this->functions_.back());
759 of.blocks.push_back(block);
763 this->init_functions_.push_back(ret);
764 this->need_init_fn_ = true;
770 // Finish compiling a function.
773 Gogo::finish_function(source_location location)
775 this->finish_block(location);
776 gcc_assert(this->functions_.back().blocks.empty());
777 this->functions_.pop_back();
780 // Return the current function.
783 Gogo::current_function() const
785 gcc_assert(!this->functions_.empty());
786 return this->functions_.back().function;
789 // Start a new block.
792 Gogo::start_block(source_location location)
794 gcc_assert(!this->functions_.empty());
795 Block* block = new Block(this->current_block(), location);
796 this->functions_.back().blocks.push_back(block);
802 Gogo::finish_block(source_location location)
804 gcc_assert(!this->functions_.empty());
805 gcc_assert(!this->functions_.back().blocks.empty());
806 Block* block = this->functions_.back().blocks.back();
807 this->functions_.back().blocks.pop_back();
808 block->set_end_location(location);
812 // Add an unknown name.
815 Gogo::add_unknown_name(const std::string& name, source_location location)
817 return this->package_->bindings()->add_unknown_name(name, location);
820 // Declare a function.
823 Gogo::declare_function(const std::string& name, Function_type* type,
824 source_location location)
826 if (!type->is_method())
827 return this->current_bindings()->add_function_declaration(name, NULL, type,
831 // We don't bother to add this to the list of global
833 Type* rtype = type->receiver()->type();
835 // We want to look through the pointer created by the
836 // parser, without getting an error if the type is not yet
838 if (rtype->classification() == Type::TYPE_POINTER)
839 rtype = rtype->points_to();
841 if (rtype->is_error_type())
843 else if (rtype->named_type() != NULL)
844 return rtype->named_type()->add_method_declaration(name, NULL, type,
846 else if (rtype->forward_declaration_type() != NULL)
848 Forward_declaration_type* ftype = rtype->forward_declaration_type();
849 return ftype->add_method_declaration(name, type, location);
856 // Add a label definition.
859 Gogo::add_label_definition(const std::string& label_name,
860 source_location location)
862 gcc_assert(!this->functions_.empty());
863 Function* func = this->functions_.back().function->func_value();
864 Label* label = func->add_label_definition(label_name, location);
865 this->add_statement(Statement::make_label_statement(label, location));
869 // Add a label reference.
872 Gogo::add_label_reference(const std::string& label_name)
874 gcc_assert(!this->functions_.empty());
875 Function* func = this->functions_.back().function->func_value();
876 return func->add_label_reference(label_name);
882 Gogo::add_statement(Statement* statement)
884 gcc_assert(!this->functions_.empty()
885 && !this->functions_.back().blocks.empty());
886 this->functions_.back().blocks.back()->add_statement(statement);
892 Gogo::add_block(Block* block, source_location location)
894 gcc_assert(!this->functions_.empty()
895 && !this->functions_.back().blocks.empty());
896 Statement* statement = Statement::make_block_statement(block, location);
897 this->functions_.back().blocks.back()->add_statement(statement);
903 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
906 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
912 Gogo::add_type(const std::string& name, Type* type, source_location location)
914 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
916 if (!this->in_global_scope() && no->is_type())
917 no->type_value()->set_in_function(this->functions_.back().function);
923 Gogo::add_named_type(Named_type* type)
925 gcc_assert(this->in_global_scope());
926 this->current_bindings()->add_named_type(type);
932 Gogo::declare_type(const std::string& name, source_location location)
934 Bindings* bindings = this->current_bindings();
935 Named_object* no = bindings->add_type_declaration(name, NULL, location);
936 if (!this->in_global_scope() && no->is_type_declaration())
938 Named_object* f = this->functions_.back().function;
939 no->type_declaration_value()->set_in_function(f);
944 // Declare a type at the package level.
947 Gogo::declare_package_type(const std::string& name, source_location location)
949 return this->package_->bindings()->add_type_declaration(name, NULL, location);
952 // Define a type which was already declared.
955 Gogo::define_type(Named_object* no, Named_type* type)
957 this->current_bindings()->define_type(no, type);
963 Gogo::add_variable(const std::string& name, Variable* variable)
965 Named_object* no = this->current_bindings()->add_variable(name, NULL,
968 // In a function the middle-end wants to see a DECL_EXPR node.
971 && !no->var_value()->is_parameter()
972 && !this->functions_.empty())
973 this->add_statement(Statement::make_variable_declaration(no));
978 // Add a sink--a reference to the blank identifier _.
983 return Named_object::make_sink();
986 // Add a named object.
989 Gogo::add_named_object(Named_object* no)
991 this->current_bindings()->add_named_object(no);
994 // Record that we've seen an interface type.
997 Gogo::record_interface_type(Interface_type* itype)
999 this->interface_types_.push_back(itype);
1002 // Return a name for a thunk object.
1007 static int thunk_count;
1008 char thunk_name[50];
1009 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1014 // Return whether a function is a thunk.
1017 Gogo::is_thunk(const Named_object* no)
1019 return no->name().compare(0, 6, "$thunk") == 0;
1022 // Define the global names. We do this only after parsing all the
1023 // input files, because the program might define the global names
1027 Gogo::define_global_names()
1029 for (Bindings::const_declarations_iterator p =
1030 this->globals_->begin_declarations();
1031 p != this->globals_->end_declarations();
1034 Named_object* global_no = p->second;
1035 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1036 Named_object* no = this->package_->bindings()->lookup(name);
1040 if (no->is_type_declaration())
1042 if (global_no->is_type())
1044 if (no->type_declaration_value()->has_methods())
1045 error_at(no->location(),
1046 "may not define methods for global type");
1047 no->set_type_value(global_no->type_value());
1051 error_at(no->location(), "expected type");
1052 Type* errtype = Type::make_error_type();
1053 Named_object* err = Named_object::make_type("error", NULL,
1056 no->set_type_value(err->type_value());
1059 else if (no->is_unknown())
1060 no->unknown_value()->set_real_named_object(global_no);
1064 // Clear out names in file scope.
1067 Gogo::clear_file_scope()
1069 this->package_->bindings()->clear_file_scope();
1071 // Warn about packages which were imported but not used.
1072 for (Packages::iterator p = this->packages_.begin();
1073 p != this->packages_.end();
1076 Package* package = p->second;
1077 if (package != this->package_
1078 && package->is_imported()
1080 && !package->uses_sink_alias()
1082 error_at(package->location(), "imported and not used: %s",
1083 Gogo::message_name(package->name()).c_str());
1084 package->clear_is_imported();
1085 package->clear_uses_sink_alias();
1086 package->clear_used();
1090 // Traverse the tree.
1093 Gogo::traverse(Traverse* traverse)
1095 // Traverse the current package first for consistency. The other
1096 // packages will only contain imported types, constants, and
1098 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1100 for (Packages::const_iterator p = this->packages_.begin();
1101 p != this->packages_.end();
1104 if (p->second != this->package_)
1106 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1112 // Traversal class used to verify types.
1114 class Verify_types : public Traverse
1118 : Traverse(traverse_types)
1125 // Verify that a type is correct.
1128 Verify_types::type(Type* t)
1131 return TRAVERSE_SKIP_COMPONENTS;
1132 return TRAVERSE_CONTINUE;
1135 // Verify that all types are correct.
1138 Gogo::verify_types()
1140 Verify_types traverse;
1141 this->traverse(&traverse);
1144 // Traversal class used to lower parse tree.
1146 class Lower_parse_tree : public Traverse
1149 Lower_parse_tree(Gogo* gogo, Named_object* function)
1150 : Traverse(traverse_variables
1151 | traverse_constants
1152 | traverse_functions
1153 | traverse_statements
1154 | traverse_expressions),
1155 gogo_(gogo), function_(function), iota_value_(-1)
1159 variable(Named_object*);
1162 constant(Named_object*, bool);
1165 function(Named_object*);
1168 statement(Block*, size_t* pindex, Statement*);
1171 expression(Expression**);
1176 // The function we are traversing.
1177 Named_object* function_;
1178 // Value to use for the predeclared constant iota.
1182 // Lower variables. We handle variables specially to break loops in
1183 // which a variable initialization expression refers to itself. The
1184 // loop breaking is in lower_init_expression.
1187 Lower_parse_tree::variable(Named_object* no)
1189 if (no->is_variable())
1190 no->var_value()->lower_init_expression(this->gogo_, this->function_);
1191 return TRAVERSE_CONTINUE;
1194 // Lower constants. We handle constants specially so that we can set
1195 // the right value for the predeclared constant iota. This works in
1196 // conjunction with the way we lower Const_expression objects.
1199 Lower_parse_tree::constant(Named_object* no, bool)
1201 Named_constant* nc = no->const_value();
1203 // Don't get into trouble if the constant's initializer expression
1204 // refers to the constant itself.
1206 return TRAVERSE_CONTINUE;
1209 gcc_assert(this->iota_value_ == -1);
1210 this->iota_value_ = nc->iota_value();
1211 nc->traverse_expression(this);
1212 this->iota_value_ = -1;
1214 nc->clear_lowering();
1216 // We will traverse the expression a second time, but that will be
1219 return TRAVERSE_CONTINUE;
1222 // Lower function closure types. Record the function while lowering
1223 // it, so that we can pass it down when lowering an expression.
1226 Lower_parse_tree::function(Named_object* no)
1228 no->func_value()->set_closure_type();
1230 gcc_assert(this->function_ == NULL);
1231 this->function_ = no;
1232 int t = no->func_value()->traverse(this);
1233 this->function_ = NULL;
1235 if (t == TRAVERSE_EXIT)
1237 return TRAVERSE_SKIP_COMPONENTS;
1240 // Lower statement parse trees.
1243 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1245 // Lower the expressions first.
1246 int t = sorig->traverse_contents(this);
1247 if (t == TRAVERSE_EXIT)
1250 // Keep lowering until nothing changes.
1251 Statement* s = sorig;
1254 Statement* snew = s->lower(this->gogo_, this->function_, block);
1258 t = s->traverse_contents(this);
1259 if (t == TRAVERSE_EXIT)
1264 block->replace_statement(*pindex, s);
1266 return TRAVERSE_SKIP_COMPONENTS;
1269 // Lower expression parse trees.
1272 Lower_parse_tree::expression(Expression** pexpr)
1274 // We have to lower all subexpressions first, so that we can get
1275 // their type if necessary. This is awkward, because we don't have
1276 // a postorder traversal pass.
1277 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1278 return TRAVERSE_EXIT;
1279 // Keep lowering until nothing changes.
1282 Expression* e = *pexpr;
1283 Expression* enew = e->lower(this->gogo_, this->function_,
1289 return TRAVERSE_SKIP_COMPONENTS;
1292 // Lower the parse tree. This is called after the parse is complete,
1293 // when all names should be resolved.
1296 Gogo::lower_parse_tree()
1298 Lower_parse_tree lower_parse_tree(this, NULL);
1299 this->traverse(&lower_parse_tree);
1305 Gogo::lower_block(Named_object* function, Block* block)
1307 Lower_parse_tree lower_parse_tree(this, function);
1308 block->traverse(&lower_parse_tree);
1311 // Lower an expression.
1314 Gogo::lower_expression(Named_object* function, Expression** pexpr)
1316 Lower_parse_tree lower_parse_tree(this, function);
1317 lower_parse_tree.expression(pexpr);
1320 // Lower a constant. This is called when lowering a reference to a
1321 // constant. We have to make sure that the constant has already been
1325 Gogo::lower_constant(Named_object* no)
1327 gcc_assert(no->is_const());
1328 Lower_parse_tree lower(this, NULL);
1329 lower.constant(no, false);
1332 // Look for interface types to finalize methods of inherited
1335 class Finalize_methods : public Traverse
1338 Finalize_methods(Gogo* gogo)
1339 : Traverse(traverse_types),
1350 // Finalize the methods of an interface type.
1353 Finalize_methods::type(Type* t)
1355 // Check the classification so that we don't finalize the methods
1356 // twice for a named interface type.
1357 switch (t->classification())
1359 case Type::TYPE_INTERFACE:
1360 t->interface_type()->finalize_methods();
1363 case Type::TYPE_NAMED:
1365 // We have to finalize the methods of the real type first.
1366 // But if the real type is a struct type, then we only want to
1367 // finalize the methods of the field types, not of the struct
1368 // type itself. We don't want to add methods to the struct,
1369 // since it has a name.
1370 Type* rt = t->named_type()->real_type();
1371 if (rt->classification() != Type::TYPE_STRUCT)
1373 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1374 return TRAVERSE_EXIT;
1378 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1379 return TRAVERSE_EXIT;
1382 t->named_type()->finalize_methods(this->gogo_);
1384 return TRAVERSE_SKIP_COMPONENTS;
1387 case Type::TYPE_STRUCT:
1388 t->struct_type()->finalize_methods(this->gogo_);
1395 return TRAVERSE_CONTINUE;
1398 // Finalize method lists and build stub methods for types.
1401 Gogo::finalize_methods()
1403 Finalize_methods finalize(this);
1404 this->traverse(&finalize);
1407 // Set types for unspecified variables and constants.
1410 Gogo::determine_types()
1412 Bindings* bindings = this->current_bindings();
1413 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1414 p != bindings->end_definitions();
1417 if ((*p)->is_function())
1418 (*p)->func_value()->determine_types();
1419 else if ((*p)->is_variable())
1420 (*p)->var_value()->determine_type();
1421 else if ((*p)->is_const())
1422 (*p)->const_value()->determine_type();
1424 // See if a variable requires us to build an initialization
1425 // function. We know that we will see all global variables
1427 if (!this->need_init_fn_ && (*p)->is_variable())
1429 Variable* variable = (*p)->var_value();
1431 // If this is a global variable which requires runtime
1432 // initialization, we need an initialization function.
1433 if (!variable->is_global())
1435 else if (variable->init() == NULL)
1437 else if (variable->type()->interface_type() != NULL)
1438 this->need_init_fn_ = true;
1439 else if (variable->init()->is_constant())
1441 else if (!variable->init()->is_composite_literal())
1442 this->need_init_fn_ = true;
1443 else if (variable->init()->is_nonconstant_composite_literal())
1444 this->need_init_fn_ = true;
1446 // If this is a global variable which holds a pointer value,
1447 // then we need an initialization function to register it as a
1449 if (variable->is_global() && variable->type()->has_pointer())
1450 this->need_init_fn_ = true;
1454 // Determine the types of constants in packages.
1455 for (Packages::const_iterator p = this->packages_.begin();
1456 p != this->packages_.end();
1458 p->second->determine_types();
1461 // Traversal class used for type checking.
1463 class Check_types_traverse : public Traverse
1466 Check_types_traverse(Gogo* gogo)
1467 : Traverse(traverse_variables
1468 | traverse_constants
1469 | traverse_functions
1470 | traverse_statements
1471 | traverse_expressions),
1476 variable(Named_object*);
1479 constant(Named_object*, bool);
1482 function(Named_object*);
1485 statement(Block*, size_t* pindex, Statement*);
1488 expression(Expression**);
1495 // Check that a variable initializer has the right type.
1498 Check_types_traverse::variable(Named_object* named_object)
1500 if (named_object->is_variable())
1502 Variable* var = named_object->var_value();
1503 Expression* init = var->init();
1506 && !Type::are_assignable(var->type(), init->type(), &reason))
1509 error_at(var->location(), "incompatible type in initialization");
1511 error_at(var->location(),
1512 "incompatible type in initialization (%s)",
1517 return TRAVERSE_CONTINUE;
1520 // Check that a constant initializer has the right type.
1523 Check_types_traverse::constant(Named_object* named_object, bool)
1525 Named_constant* constant = named_object->const_value();
1526 Type* ctype = constant->type();
1527 if (ctype->integer_type() == NULL
1528 && ctype->float_type() == NULL
1529 && ctype->complex_type() == NULL
1530 && !ctype->is_boolean_type()
1531 && !ctype->is_string_type())
1533 if (ctype->is_nil_type())
1534 error_at(constant->location(), "const initializer cannot be nil");
1535 else if (!ctype->is_error())
1536 error_at(constant->location(), "invalid constant type");
1537 constant->set_error();
1539 else if (!constant->expr()->is_constant())
1541 error_at(constant->expr()->location(), "expression is not constant");
1542 constant->set_error();
1544 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1547 error_at(constant->location(),
1548 "initialization expression has wrong type");
1549 constant->set_error();
1551 return TRAVERSE_CONTINUE;
1554 // There are no types to check in a function, but this is where we
1555 // issue warnings about labels which are defined but not referenced.
1558 Check_types_traverse::function(Named_object* no)
1560 no->func_value()->check_labels();
1561 return TRAVERSE_CONTINUE;
1564 // Check that types are valid in a statement.
1567 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1569 s->check_types(this->gogo_);
1570 return TRAVERSE_CONTINUE;
1573 // Check that types are valid in an expression.
1576 Check_types_traverse::expression(Expression** expr)
1578 (*expr)->check_types(this->gogo_);
1579 return TRAVERSE_CONTINUE;
1582 // Check that types are valid.
1587 Check_types_traverse traverse(this);
1588 this->traverse(&traverse);
1591 // Check the types in a single block.
1594 Gogo::check_types_in_block(Block* block)
1596 Check_types_traverse traverse(this);
1597 block->traverse(&traverse);
1600 // A traversal class used to find a single shortcut operator within an
1603 class Find_shortcut : public Traverse
1607 : Traverse(traverse_blocks
1608 | traverse_statements
1609 | traverse_expressions),
1613 // A pointer to the expression which was found, or NULL if none was
1617 { return this->found_; }
1622 { return TRAVERSE_SKIP_COMPONENTS; }
1625 statement(Block*, size_t*, Statement*)
1626 { return TRAVERSE_SKIP_COMPONENTS; }
1629 expression(Expression**);
1632 Expression** found_;
1635 // Find a shortcut expression.
1638 Find_shortcut::expression(Expression** pexpr)
1640 Expression* expr = *pexpr;
1641 Binary_expression* be = expr->binary_expression();
1643 return TRAVERSE_CONTINUE;
1644 Operator op = be->op();
1645 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1646 return TRAVERSE_CONTINUE;
1647 gcc_assert(this->found_ == NULL);
1648 this->found_ = pexpr;
1649 return TRAVERSE_EXIT;
1652 // A traversal class used to turn shortcut operators into explicit if
1655 class Shortcuts : public Traverse
1658 Shortcuts(Gogo* gogo)
1659 : Traverse(traverse_variables
1660 | traverse_statements),
1666 variable(Named_object*);
1669 statement(Block*, size_t*, Statement*);
1672 // Convert a shortcut operator.
1674 convert_shortcut(Block* enclosing, Expression** pshortcut);
1680 // Remove shortcut operators in a single statement.
1683 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1685 // FIXME: This approach doesn't work for switch statements, because
1686 // we add the new statements before the whole switch when we need to
1687 // instead add them just before the switch expression. The right
1688 // fix is probably to lower switch statements with nonconstant cases
1689 // to a series of conditionals.
1690 if (s->switch_statement() != NULL)
1691 return TRAVERSE_CONTINUE;
1695 Find_shortcut find_shortcut;
1697 // If S is a variable declaration, then ordinary traversal won't
1698 // do anything. We want to explicitly traverse the
1699 // initialization expression if there is one.
1700 Variable_declaration_statement* vds = s->variable_declaration_statement();
1701 Expression* init = NULL;
1703 s->traverse_contents(&find_shortcut);
1706 init = vds->var()->var_value()->init();
1708 return TRAVERSE_CONTINUE;
1709 init->traverse(&init, &find_shortcut);
1711 Expression** pshortcut = find_shortcut.found();
1712 if (pshortcut == NULL)
1713 return TRAVERSE_CONTINUE;
1715 Statement* snew = this->convert_shortcut(block, pshortcut);
1716 block->insert_statement_before(*pindex, snew);
1719 if (pshortcut == &init)
1720 vds->var()->var_value()->set_init(init);
1724 // Remove shortcut operators in the initializer of a global variable.
1727 Shortcuts::variable(Named_object* no)
1729 if (no->is_result_variable())
1730 return TRAVERSE_CONTINUE;
1731 Variable* var = no->var_value();
1732 Expression* init = var->init();
1733 if (!var->is_global() || init == NULL)
1734 return TRAVERSE_CONTINUE;
1738 Find_shortcut find_shortcut;
1739 init->traverse(&init, &find_shortcut);
1740 Expression** pshortcut = find_shortcut.found();
1741 if (pshortcut == NULL)
1742 return TRAVERSE_CONTINUE;
1744 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1745 var->add_preinit_statement(this->gogo_, snew);
1746 if (pshortcut == &init)
1747 var->set_init(init);
1751 // Given an expression which uses a shortcut operator, return a
1752 // statement which implements it, and update *PSHORTCUT accordingly.
1755 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1757 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1758 Expression* left = shortcut->left();
1759 Expression* right = shortcut->right();
1760 source_location loc = shortcut->location();
1762 Block* retblock = new Block(enclosing, loc);
1763 retblock->set_end_location(loc);
1765 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
1767 retblock->add_statement(ts);
1769 Block* block = new Block(retblock, loc);
1770 block->set_end_location(loc);
1771 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1772 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1773 block->add_statement(assign);
1775 Expression* cond = Expression::make_temporary_reference(ts, loc);
1776 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1777 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1779 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1781 retblock->add_statement(if_statement);
1783 *pshortcut = Expression::make_temporary_reference(ts, loc);
1787 // Now convert any shortcut operators in LEFT and RIGHT.
1788 Shortcuts shortcuts(this->gogo_);
1789 retblock->traverse(&shortcuts);
1791 return Statement::make_block_statement(retblock, loc);
1794 // Turn shortcut operators into explicit if statements. Doing this
1795 // considerably simplifies the order of evaluation rules.
1798 Gogo::remove_shortcuts()
1800 Shortcuts shortcuts(this);
1801 this->traverse(&shortcuts);
1804 // A traversal class which finds all the expressions which must be
1805 // evaluated in order within a statement or larger expression. This
1806 // is used to implement the rules about order of evaluation.
1808 class Find_eval_ordering : public Traverse
1811 typedef std::vector<Expression**> Expression_pointers;
1814 Find_eval_ordering()
1815 : Traverse(traverse_blocks
1816 | traverse_statements
1817 | traverse_expressions),
1823 { return this->exprs_.size(); }
1825 typedef Expression_pointers::const_iterator const_iterator;
1829 { return this->exprs_.begin(); }
1833 { return this->exprs_.end(); }
1838 { return TRAVERSE_SKIP_COMPONENTS; }
1841 statement(Block*, size_t*, Statement*)
1842 { return TRAVERSE_SKIP_COMPONENTS; }
1845 expression(Expression**);
1848 // A list of pointers to expressions with side-effects.
1849 Expression_pointers exprs_;
1852 // If an expression must be evaluated in order, put it on the list.
1855 Find_eval_ordering::expression(Expression** expression_pointer)
1857 // We have to look at subexpressions before this one.
1858 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1859 return TRAVERSE_EXIT;
1860 if ((*expression_pointer)->must_eval_in_order())
1861 this->exprs_.push_back(expression_pointer);
1862 return TRAVERSE_SKIP_COMPONENTS;
1865 // A traversal class for ordering evaluations.
1867 class Order_eval : public Traverse
1870 Order_eval(Gogo* gogo)
1871 : Traverse(traverse_variables
1872 | traverse_statements),
1877 variable(Named_object*);
1880 statement(Block*, size_t*, Statement*);
1887 // Implement the order of evaluation rules for a statement.
1890 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1892 // FIXME: This approach doesn't work for switch statements, because
1893 // we add the new statements before the whole switch when we need to
1894 // instead add them just before the switch expression. The right
1895 // fix is probably to lower switch statements with nonconstant cases
1896 // to a series of conditionals.
1897 if (s->switch_statement() != NULL)
1898 return TRAVERSE_CONTINUE;
1900 Find_eval_ordering find_eval_ordering;
1902 // If S is a variable declaration, then ordinary traversal won't do
1903 // anything. We want to explicitly traverse the initialization
1904 // expression if there is one.
1905 Variable_declaration_statement* vds = s->variable_declaration_statement();
1906 Expression* init = NULL;
1907 Expression* orig_init = NULL;
1909 s->traverse_contents(&find_eval_ordering);
1912 init = vds->var()->var_value()->init();
1914 return TRAVERSE_CONTINUE;
1917 // It might seem that this could be
1918 // init->traverse_subexpressions. Unfortunately that can fail
1921 // newvar, err := call(arg())
1922 // Here newvar will have an init of call result 0 of
1923 // call(arg()). If we only traverse subexpressions, we will
1924 // only find arg(), and we won't bother to move anything out.
1925 // Then we get to the assignment to err, we will traverse the
1926 // whole statement, and this time we will find both call() and
1927 // arg(), and so we will move them out. This will cause them to
1928 // be put into temporary variables before the assignment to err
1929 // but after the declaration of newvar. To avoid that problem,
1930 // we traverse the entire expression here.
1931 Expression::traverse(&init, &find_eval_ordering);
1934 if (find_eval_ordering.size() <= 1)
1936 // If there is only one expression with a side-effect, we can
1937 // leave it in place.
1938 return TRAVERSE_CONTINUE;
1941 bool is_thunk = s->thunk_statement() != NULL;
1942 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1943 p != find_eval_ordering.end();
1946 Expression** pexpr = *p;
1948 // The last expression in a thunk will be the call passed to go
1949 // or defer, which we must not evaluate early.
1950 if (is_thunk && p + 1 == find_eval_ordering.end())
1953 source_location loc = (*pexpr)->location();
1954 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1955 block->insert_statement_before(*pindex, ts);
1958 *pexpr = Expression::make_temporary_reference(ts, loc);
1961 if (init != orig_init)
1962 vds->var()->var_value()->set_init(init);
1964 return TRAVERSE_CONTINUE;
1967 // Implement the order of evaluation rules for the initializer of a
1971 Order_eval::variable(Named_object* no)
1973 if (no->is_result_variable())
1974 return TRAVERSE_CONTINUE;
1975 Variable* var = no->var_value();
1976 Expression* init = var->init();
1977 if (!var->is_global() || init == NULL)
1978 return TRAVERSE_CONTINUE;
1980 Find_eval_ordering find_eval_ordering;
1981 init->traverse_subexpressions(&find_eval_ordering);
1983 if (find_eval_ordering.size() <= 1)
1985 // If there is only one expression with a side-effect, we can
1986 // leave it in place.
1987 return TRAVERSE_SKIP_COMPONENTS;
1990 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1991 p != find_eval_ordering.end();
1994 Expression** pexpr = *p;
1995 source_location loc = (*pexpr)->location();
1996 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1997 var->add_preinit_statement(this->gogo_, ts);
1998 *pexpr = Expression::make_temporary_reference(ts, loc);
2001 return TRAVERSE_SKIP_COMPONENTS;
2004 // Use temporary variables to implement the order of evaluation rules.
2007 Gogo::order_evaluations()
2009 Order_eval order_eval(this);
2010 this->traverse(&order_eval);
2013 // Traversal to convert calls to the predeclared recover function to
2014 // pass in an argument indicating whether it can recover from a panic
2017 class Convert_recover : public Traverse
2020 Convert_recover(Named_object* arg)
2021 : Traverse(traverse_expressions),
2027 expression(Expression**);
2030 // The argument to pass to the function.
2034 // Convert calls to recover.
2037 Convert_recover::expression(Expression** pp)
2039 Call_expression* ce = (*pp)->call_expression();
2040 if (ce != NULL && ce->is_recover_call())
2041 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2043 return TRAVERSE_CONTINUE;
2046 // Traversal for build_recover_thunks.
2048 class Build_recover_thunks : public Traverse
2051 Build_recover_thunks(Gogo* gogo)
2052 : Traverse(traverse_functions),
2057 function(Named_object*);
2061 can_recover_arg(source_location);
2067 // If this function calls recover, turn it into a thunk.
2070 Build_recover_thunks::function(Named_object* orig_no)
2072 Function* orig_func = orig_no->func_value();
2073 if (!orig_func->calls_recover()
2074 || orig_func->is_recover_thunk()
2075 || orig_func->has_recover_thunk())
2076 return TRAVERSE_CONTINUE;
2078 Gogo* gogo = this->gogo_;
2079 source_location location = orig_func->location();
2084 Function_type* orig_fntype = orig_func->type();
2085 Typed_identifier_list* new_params = new Typed_identifier_list();
2086 std::string receiver_name;
2087 if (orig_fntype->is_method())
2089 const Typed_identifier* receiver = orig_fntype->receiver();
2090 snprintf(buf, sizeof buf, "rt.%u", count);
2092 receiver_name = buf;
2093 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2094 receiver->location()));
2096 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2097 if (orig_params != NULL && !orig_params->empty())
2099 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2100 p != orig_params->end();
2103 snprintf(buf, sizeof buf, "pt.%u", count);
2105 new_params->push_back(Typed_identifier(buf, p->type(),
2109 snprintf(buf, sizeof buf, "pr.%u", count);
2111 std::string can_recover_name = buf;
2112 new_params->push_back(Typed_identifier(can_recover_name,
2113 Type::lookup_bool_type(),
2114 orig_fntype->location()));
2116 const Typed_identifier_list* orig_results = orig_fntype->results();
2117 Typed_identifier_list* new_results;
2118 if (orig_results == NULL || orig_results->empty())
2122 new_results = new Typed_identifier_list();
2123 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2124 p != orig_results->end();
2126 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2129 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2131 orig_fntype->location());
2132 if (orig_fntype->is_varargs())
2133 new_fntype->set_is_varargs();
2135 std::string name = orig_no->name() + "$recover";
2136 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2138 Function *new_func = new_no->func_value();
2139 if (orig_func->enclosing() != NULL)
2140 new_func->set_enclosing(orig_func->enclosing());
2142 // We build the code for the original function attached to the new
2143 // function, and then swap the original and new function bodies.
2144 // This means that existing references to the original function will
2145 // then refer to the new function. That makes this code a little
2146 // confusing, in that the reference to NEW_NO really refers to the
2147 // other function, not the one we are building.
2149 Expression* closure = NULL;
2150 if (orig_func->needs_closure())
2152 Named_object* orig_closure_no = orig_func->closure_var();
2153 Variable* orig_closure_var = orig_closure_no->var_value();
2154 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2155 true, false, location);
2156 snprintf(buf, sizeof buf, "closure.%u", count);
2158 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2160 new_func->set_closure_var(new_closure_no);
2161 closure = Expression::make_var_reference(new_closure_no, location);
2164 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2166 Expression_list* args = new Expression_list();
2167 if (new_params != NULL)
2169 // Note that we skip the last parameter, which is the boolean
2170 // indicating whether recover can succed.
2171 for (Typed_identifier_list::const_iterator p = new_params->begin();
2172 p + 1 != new_params->end();
2175 Named_object* p_no = gogo->lookup(p->name(), NULL);
2176 gcc_assert(p_no != NULL
2177 && p_no->is_variable()
2178 && p_no->var_value()->is_parameter());
2179 args->push_back(Expression::make_var_reference(p_no, location));
2182 args->push_back(this->can_recover_arg(location));
2184 Call_expression* call = Expression::make_call(fn, args, false, location);
2187 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2188 s = Statement::make_statement(call);
2191 Expression_list* vals = new Expression_list();
2192 size_t rc = orig_fntype->results()->size();
2194 vals->push_back(call);
2197 for (size_t i = 0; i < rc; ++i)
2198 vals->push_back(Expression::make_call_result(call, i));
2200 s = Statement::make_return_statement(vals, location);
2202 s->determine_types();
2203 gogo->add_statement(s);
2205 gogo->finish_function(location);
2207 // Swap the function bodies and types.
2208 new_func->swap_for_recover(orig_func);
2209 orig_func->set_is_recover_thunk();
2210 new_func->set_calls_recover();
2211 new_func->set_has_recover_thunk();
2213 Bindings* orig_bindings = orig_func->block()->bindings();
2214 Bindings* new_bindings = new_func->block()->bindings();
2215 if (orig_fntype->is_method())
2217 // We changed the receiver to be a regular parameter. We have
2218 // to update the binding accordingly in both functions.
2219 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2220 gcc_assert(orig_rec_no != NULL
2221 && orig_rec_no->is_variable()
2222 && !orig_rec_no->var_value()->is_receiver());
2223 orig_rec_no->var_value()->set_is_receiver();
2225 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2226 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2227 if (new_rec_no == NULL)
2228 gcc_assert(saw_errors());
2231 gcc_assert(new_rec_no->is_variable()
2232 && new_rec_no->var_value()->is_receiver());
2233 new_rec_no->var_value()->set_is_not_receiver();
2237 // Because we flipped blocks but not types, the can_recover
2238 // parameter appears in the (now) old bindings as a parameter.
2239 // Change it to a local variable, whereupon it will be discarded.
2240 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2241 gcc_assert(can_recover_no != NULL
2242 && can_recover_no->is_variable()
2243 && can_recover_no->var_value()->is_parameter());
2244 orig_bindings->remove_binding(can_recover_no);
2246 // Add the can_recover argument to the (now) new bindings, and
2247 // attach it to any recover statements.
2248 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2249 false, true, false, location);
2250 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2252 Convert_recover convert_recover(can_recover_no);
2253 new_func->traverse(&convert_recover);
2255 // Update the function pointers in any named results.
2256 new_func->update_result_variables();
2257 orig_func->update_result_variables();
2259 return TRAVERSE_CONTINUE;
2262 // Return the expression to pass for the .can_recover parameter to the
2263 // new function. This indicates whether a call to recover may return
2264 // non-nil. The expression is
2265 // __go_can_recover(__builtin_return_address()).
2268 Build_recover_thunks::can_recover_arg(source_location location)
2270 static Named_object* builtin_return_address;
2271 if (builtin_return_address == NULL)
2273 const source_location bloc = BUILTINS_LOCATION;
2275 Typed_identifier_list* param_types = new Typed_identifier_list();
2276 Type* uint_type = Type::lookup_integer_type("uint");
2277 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2279 Typed_identifier_list* return_types = new Typed_identifier_list();
2280 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2281 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2283 Function_type* fntype = Type::make_function_type(NULL, param_types,
2284 return_types, bloc);
2285 builtin_return_address =
2286 Named_object::make_function_declaration("__builtin_return_address",
2287 NULL, fntype, bloc);
2288 const char* n = "__builtin_return_address";
2289 builtin_return_address->func_declaration_value()->set_asm_name(n);
2292 static Named_object* can_recover;
2293 if (can_recover == NULL)
2295 const source_location bloc = BUILTINS_LOCATION;
2296 Typed_identifier_list* param_types = new Typed_identifier_list();
2297 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2298 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2299 Type* boolean_type = Type::lookup_bool_type();
2300 Typed_identifier_list* results = new Typed_identifier_list();
2301 results->push_back(Typed_identifier("", boolean_type, bloc));
2302 Function_type* fntype = Type::make_function_type(NULL, param_types,
2304 can_recover = Named_object::make_function_declaration("__go_can_recover",
2307 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2310 Expression* fn = Expression::make_func_reference(builtin_return_address,
2314 mpz_init_set_ui(zval, 0UL);
2315 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2317 Expression_list *args = new Expression_list();
2318 args->push_back(zexpr);
2320 Expression* call = Expression::make_call(fn, args, false, location);
2322 args = new Expression_list();
2323 args->push_back(call);
2325 fn = Expression::make_func_reference(can_recover, NULL, location);
2326 return Expression::make_call(fn, args, false, location);
2329 // Build thunks for functions which call recover. We build a new
2330 // function with an extra parameter, which is whether a call to
2331 // recover can succeed. We then move the body of this function to
2332 // that one. We then turn this function into a thunk which calls the
2333 // new one, passing the value of
2334 // __go_can_recover(__builtin_return_address()). The function will be
2335 // marked as not splitting the stack. This will cooperate with the
2336 // implementation of defer to make recover do the right thing.
2339 Gogo::build_recover_thunks()
2341 Build_recover_thunks build_recover_thunks(this);
2342 this->traverse(&build_recover_thunks);
2345 // Look for named types to see whether we need to create an interface
2348 class Build_method_tables : public Traverse
2351 Build_method_tables(Gogo* gogo,
2352 const std::vector<Interface_type*>& interfaces)
2353 : Traverse(traverse_types),
2354 gogo_(gogo), interfaces_(interfaces)
2363 // A list of locally defined interfaces which have hidden methods.
2364 const std::vector<Interface_type*>& interfaces_;
2367 // Build all required interface method tables for types. We need to
2368 // ensure that we have an interface method table for every interface
2369 // which has a hidden method, for every named type which implements
2370 // that interface. Normally we can just build interface method tables
2371 // as we need them. However, in some cases we can require an
2372 // interface method table for an interface defined in a different
2373 // package for a type defined in that package. If that interface and
2374 // type both use a hidden method, that is OK. However, we will not be
2375 // able to build that interface method table when we need it, because
2376 // the type's hidden method will be static. So we have to build it
2377 // here, and just refer it from other packages as needed.
2380 Gogo::build_interface_method_tables()
2382 std::vector<Interface_type*> hidden_interfaces;
2383 hidden_interfaces.reserve(this->interface_types_.size());
2384 for (std::vector<Interface_type*>::const_iterator pi =
2385 this->interface_types_.begin();
2386 pi != this->interface_types_.end();
2389 const Typed_identifier_list* methods = (*pi)->methods();
2390 if (methods == NULL)
2392 for (Typed_identifier_list::const_iterator pm = methods->begin();
2393 pm != methods->end();
2396 if (Gogo::is_hidden_name(pm->name()))
2398 hidden_interfaces.push_back(*pi);
2404 if (!hidden_interfaces.empty())
2406 // Now traverse the tree looking for all named types.
2407 Build_method_tables bmt(this, hidden_interfaces);
2408 this->traverse(&bmt);
2411 // We no longer need the list of interfaces.
2413 this->interface_types_.clear();
2416 // This is called for each type. For a named type, for each of the
2417 // interfaces with hidden methods that it implements, create the
2421 Build_method_tables::type(Type* type)
2423 Named_type* nt = type->named_type();
2426 for (std::vector<Interface_type*>::const_iterator p =
2427 this->interfaces_.begin();
2428 p != this->interfaces_.end();
2431 // We ask whether a pointer to the named type implements the
2432 // interface, because a pointer can implement more methods
2434 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2436 nt->interface_method_table(this->gogo_, *p, false);
2437 nt->interface_method_table(this->gogo_, *p, true);
2441 return TRAVERSE_CONTINUE;
2444 // Traversal class used to check for return statements.
2446 class Check_return_statements_traverse : public Traverse
2449 Check_return_statements_traverse()
2450 : Traverse(traverse_functions)
2454 function(Named_object*);
2457 // Check that a function has a return statement if it needs one.
2460 Check_return_statements_traverse::function(Named_object* no)
2462 Function* func = no->func_value();
2463 const Function_type* fntype = func->type();
2464 const Typed_identifier_list* results = fntype->results();
2466 // We only need a return statement if there is a return value.
2467 if (results == NULL || results->empty())
2468 return TRAVERSE_CONTINUE;
2470 if (func->block()->may_fall_through())
2471 error_at(func->location(), "control reaches end of non-void function");
2473 return TRAVERSE_CONTINUE;
2476 // Check return statements.
2479 Gogo::check_return_statements()
2481 Check_return_statements_traverse traverse;
2482 this->traverse(&traverse);
2485 // Get the unique prefix to use before all exported symbols. This
2486 // must be unique across the entire link.
2489 Gogo::unique_prefix() const
2491 gcc_assert(!this->unique_prefix_.empty());
2492 return this->unique_prefix_;
2495 // Set the unique prefix to use before all exported symbols. This
2496 // comes from the command line option -fgo-prefix=XXX.
2499 Gogo::set_unique_prefix(const std::string& arg)
2501 gcc_assert(this->unique_prefix_.empty());
2502 this->unique_prefix_ = arg;
2503 this->unique_prefix_specified_ = true;
2506 // Work out the package priority. It is one more than the maximum
2507 // priority of an imported package.
2510 Gogo::package_priority() const
2513 for (Packages::const_iterator p = this->packages_.begin();
2514 p != this->packages_.end();
2516 if (p->second->priority() > priority)
2517 priority = p->second->priority();
2518 return priority + 1;
2521 // Export identifiers as requested.
2526 // For now we always stream to a section. Later we may want to
2527 // support streaming to a separate file.
2528 Stream_to_section stream;
2530 Export exp(&stream);
2531 exp.register_builtin_types(this);
2532 exp.export_globals(this->package_name(),
2533 this->unique_prefix(),
2534 this->package_priority(),
2535 (this->need_init_fn_ && !this->is_main_package()
2536 ? this->get_init_fn_name()
2538 this->imported_init_fns_,
2539 this->package_->bindings());
2542 // Find the blocks in order to convert named types defined in blocks.
2544 class Convert_named_types : public Traverse
2547 Convert_named_types(Gogo* gogo)
2548 : Traverse(traverse_blocks),
2554 block(Block* block);
2561 Convert_named_types::block(Block* block)
2563 this->gogo_->convert_named_types_in_bindings(block->bindings());
2564 return TRAVERSE_CONTINUE;
2567 // Convert all named types to the backend representation. Since named
2568 // types can refer to other types, this needs to be done in the right
2569 // sequence, which is handled by Named_type::convert. Here we arrange
2570 // to call that for each named type.
2573 Gogo::convert_named_types()
2575 this->convert_named_types_in_bindings(this->globals_);
2576 for (Packages::iterator p = this->packages_.begin();
2577 p != this->packages_.end();
2580 Package* package = p->second;
2581 this->convert_named_types_in_bindings(package->bindings());
2584 Convert_named_types cnt(this);
2585 this->traverse(&cnt);
2587 // Make all the builtin named types used for type descriptors, and
2588 // then convert them. They will only be written out if they are
2590 Type::make_type_descriptor_type();
2591 Type::make_type_descriptor_ptr_type();
2592 Function_type::make_function_type_descriptor_type();
2593 Pointer_type::make_pointer_type_descriptor_type();
2594 Struct_type::make_struct_type_descriptor_type();
2595 Array_type::make_array_type_descriptor_type();
2596 Array_type::make_slice_type_descriptor_type();
2597 Map_type::make_map_type_descriptor_type();
2598 Channel_type::make_chan_type_descriptor_type();
2599 Interface_type::make_interface_type_descriptor_type();
2600 Type::convert_builtin_named_types(this);
2602 Runtime::convert_types(this);
2604 this->named_types_are_converted_ = true;
2607 // Convert all names types in a set of bindings.
2610 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2612 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2613 p != bindings->end_definitions();
2616 if ((*p)->is_type())
2617 (*p)->type_value()->convert(this);
2623 Function::Function(Function_type* type, Function* enclosing, Block* block,
2624 source_location location)
2625 : type_(type), enclosing_(enclosing), results_(NULL),
2626 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2627 defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2628 is_recover_thunk_(false), has_recover_thunk_(false)
2632 // Create the named result variables.
2635 Function::create_result_variables(Gogo* gogo)
2637 const Typed_identifier_list* results = this->type_->results();
2638 if (results == NULL || results->empty())
2641 if (!results->front().name().empty())
2642 this->results_are_named_ = true;
2644 this->results_ = new Results();
2645 this->results_->reserve(results->size());
2647 Block* block = this->block_;
2649 for (Typed_identifier_list::const_iterator p = results->begin();
2650 p != results->end();
2653 std::string name = p->name();
2654 if (name.empty() || Gogo::is_sink_name(name))
2656 static int result_counter;
2658 snprintf(buf, sizeof buf, "$ret%d", result_counter);
2660 name = gogo->pack_hidden_name(buf, false);
2662 Result_variable* result = new Result_variable(p->type(), this, index,
2664 Named_object* no = block->bindings()->add_result_variable(name, result);
2665 if (no->is_result_variable())
2666 this->results_->push_back(no);
2669 static int dummy_result_count;
2671 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2672 ++dummy_result_count;
2673 name = gogo->pack_hidden_name(buf, false);
2674 no = block->bindings()->add_result_variable(name, result);
2675 gcc_assert(no->is_result_variable());
2676 this->results_->push_back(no);
2681 // Update the named result variables when cloning a function which
2685 Function::update_result_variables()
2687 if (this->results_ == NULL)
2690 for (Results::iterator p = this->results_->begin();
2691 p != this->results_->end();
2693 (*p)->result_var_value()->set_function(this);
2696 // Return the closure variable, creating it if necessary.
2699 Function::closure_var()
2701 if (this->closure_var_ == NULL)
2703 // We don't know the type of the variable yet. We add fields as
2705 source_location loc = this->type_->location();
2706 Struct_field_list* sfl = new Struct_field_list;
2707 Type* struct_type = Type::make_struct_type(sfl, loc);
2708 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2709 NULL, false, true, false, loc);
2710 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2711 // Note that the new variable is not in any binding contour.
2713 return this->closure_var_;
2716 // Set the type of the closure variable.
2719 Function::set_closure_type()
2721 if (this->closure_var_ == NULL)
2723 Named_object* closure = this->closure_var_;
2724 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2725 unsigned int index = 0;
2726 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2727 p != this->closure_fields_.end();
2730 Named_object* no = p->first;
2732 snprintf(buf, sizeof buf, "%u", index);
2733 std::string n = no->name() + buf;
2735 if (no->is_variable())
2736 var_type = no->var_value()->type();
2738 var_type = no->result_var_value()->type();
2739 Type* field_type = Type::make_pointer_type(var_type);
2740 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2744 // Return whether this function is a method.
2747 Function::is_method() const
2749 return this->type_->is_method();
2752 // Add a label definition.
2755 Function::add_label_definition(const std::string& label_name,
2756 source_location location)
2758 Label* lnull = NULL;
2759 std::pair<Labels::iterator, bool> ins =
2760 this->labels_.insert(std::make_pair(label_name, lnull));
2763 // This is a new label.
2764 Label* label = new Label(label_name);
2765 label->define(location);
2766 ins.first->second = label;
2771 // The label was already in the hash table.
2772 Label* label = ins.first->second;
2773 if (!label->is_defined())
2775 label->define(location);
2780 error_at(location, "label %qs already defined",
2781 Gogo::message_name(label_name).c_str());
2782 inform(label->location(), "previous definition of %qs was here",
2783 Gogo::message_name(label_name).c_str());
2784 return new Label(label_name);
2789 // Add a reference to a label.
2792 Function::add_label_reference(const std::string& label_name)
2794 Label* lnull = NULL;
2795 std::pair<Labels::iterator, bool> ins =
2796 this->labels_.insert(std::make_pair(label_name, lnull));
2799 // The label was already in the hash table.
2800 Label* label = ins.first->second;
2801 label->set_is_used();
2806 gcc_assert(ins.first->second == NULL);
2807 Label* label = new Label(label_name);
2808 ins.first->second = label;
2809 label->set_is_used();
2814 // Warn about labels that are defined but not used.
2817 Function::check_labels() const
2819 for (Labels::const_iterator p = this->labels_.begin();
2820 p != this->labels_.end();
2823 Label* label = p->second;
2824 if (!label->is_used())
2825 error_at(label->location(), "label %qs defined and not used",
2826 Gogo::message_name(label->name()).c_str());
2830 // Swap one function with another. This is used when building the
2831 // thunk we use to call a function which calls recover. It may not
2832 // work for any other case.
2835 Function::swap_for_recover(Function *x)
2837 gcc_assert(this->enclosing_ == x->enclosing_);
2838 std::swap(this->results_, x->results_);
2839 std::swap(this->closure_var_, x->closure_var_);
2840 std::swap(this->block_, x->block_);
2841 gcc_assert(this->location_ == x->location_);
2842 gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2843 gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2846 // Traverse the tree.
2849 Function::traverse(Traverse* traverse)
2851 unsigned int traverse_mask = traverse->traverse_mask();
2854 & (Traverse::traverse_types | Traverse::traverse_expressions))
2857 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2858 return TRAVERSE_EXIT;
2861 // FIXME: We should check traverse_functions here if nested
2862 // functions are stored in block bindings.
2863 if (this->block_ != NULL
2865 & (Traverse::traverse_variables
2866 | Traverse::traverse_constants
2867 | Traverse::traverse_blocks
2868 | Traverse::traverse_statements
2869 | Traverse::traverse_expressions
2870 | Traverse::traverse_types)) != 0)
2872 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2873 return TRAVERSE_EXIT;
2876 return TRAVERSE_CONTINUE;
2879 // Work out types for unspecified variables and constants.
2882 Function::determine_types()
2884 if (this->block_ != NULL)
2885 this->block_->determine_types();
2888 // Get a pointer to the variable holding the defer stack for this
2889 // function, making it if necessary. At least at present, the value
2890 // of this variable is not used. However, a pointer to this variable
2891 // is used as a marker for the functions on the defer stack associated
2892 // with this function. Doing things this way permits inlining a
2893 // function which uses defer.
2896 Function::defer_stack(source_location location)
2898 Type* t = Type::make_pointer_type(Type::make_void_type());
2899 if (this->defer_stack_ == NULL)
2901 Expression* n = Expression::make_nil(location);
2902 this->defer_stack_ = Statement::make_temporary(t, n, location);
2903 this->defer_stack_->set_is_address_taken();
2905 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
2907 Expression* addr = Expression::make_unary(OPERATOR_AND, ref, location);
2908 return Expression::make_unsafe_cast(t, addr, location);
2911 // Export the function.
2914 Function::export_func(Export* exp, const std::string& name) const
2916 Function::export_func_with_type(exp, name, this->type_);
2919 // Export a function with a type.
2922 Function::export_func_with_type(Export* exp, const std::string& name,
2923 const Function_type* fntype)
2925 exp->write_c_string("func ");
2927 if (fntype->is_method())
2929 exp->write_c_string("(");
2930 exp->write_type(fntype->receiver()->type());
2931 exp->write_c_string(") ");
2934 exp->write_string(name);
2936 exp->write_c_string(" (");
2937 const Typed_identifier_list* parameters = fntype->parameters();
2938 if (parameters != NULL)
2940 bool is_varargs = fntype->is_varargs();
2942 for (Typed_identifier_list::const_iterator p = parameters->begin();
2943 p != parameters->end();
2949 exp->write_c_string(", ");
2950 if (!is_varargs || p + 1 != parameters->end())
2951 exp->write_type(p->type());
2954 exp->write_c_string("...");
2955 exp->write_type(p->type()->array_type()->element_type());
2959 exp->write_c_string(")");
2961 const Typed_identifier_list* results = fntype->results();
2962 if (results != NULL)
2964 if (results->size() == 1)
2966 exp->write_c_string(" ");
2967 exp->write_type(results->begin()->type());
2971 exp->write_c_string(" (");
2973 for (Typed_identifier_list::const_iterator p = results->begin();
2974 p != results->end();
2980 exp->write_c_string(", ");
2981 exp->write_type(p->type());
2983 exp->write_c_string(")");
2986 exp->write_c_string(";\n");
2989 // Import a function.
2992 Function::import_func(Import* imp, std::string* pname,
2993 Typed_identifier** preceiver,
2994 Typed_identifier_list** pparameters,
2995 Typed_identifier_list** presults,
2998 imp->require_c_string("func ");
3001 if (imp->peek_char() == '(')
3003 imp->require_c_string("(");
3004 Type* rtype = imp->read_type();
3005 *preceiver = new Typed_identifier(Import::import_marker, rtype,
3007 imp->require_c_string(") ");
3010 *pname = imp->read_identifier();
3012 Typed_identifier_list* parameters;
3013 *is_varargs = false;
3014 imp->require_c_string(" (");
3015 if (imp->peek_char() == ')')
3019 parameters = new Typed_identifier_list();
3022 if (imp->match_c_string("..."))
3028 Type* ptype = imp->read_type();
3030 ptype = Type::make_array_type(ptype, NULL);
3031 parameters->push_back(Typed_identifier(Import::import_marker,
3032 ptype, imp->location()));
3033 if (imp->peek_char() != ',')
3035 gcc_assert(!*is_varargs);
3036 imp->require_c_string(", ");
3039 imp->require_c_string(")");
3040 *pparameters = parameters;
3042 Typed_identifier_list* results;
3043 if (imp->peek_char() != ' ')
3047 results = new Typed_identifier_list();
3048 imp->require_c_string(" ");
3049 if (imp->peek_char() != '(')
3051 Type* rtype = imp->read_type();
3052 results->push_back(Typed_identifier(Import::import_marker, rtype,
3057 imp->require_c_string("(");
3060 Type* rtype = imp->read_type();
3061 results->push_back(Typed_identifier(Import::import_marker,
3062 rtype, imp->location()));
3063 if (imp->peek_char() != ',')
3065 imp->require_c_string(", ");
3067 imp->require_c_string(")");
3070 imp->require_c_string(";\n");
3071 *presults = results;
3076 Block::Block(Block* enclosing, source_location location)
3077 : enclosing_(enclosing), statements_(),
3078 bindings_(new Bindings(enclosing == NULL
3080 : enclosing->bindings())),
3081 start_location_(location),
3082 end_location_(UNKNOWN_LOCATION)
3086 // Add a statement to a block.
3089 Block::add_statement(Statement* statement)
3091 this->statements_.push_back(statement);
3094 // Add a statement to the front of a block. This is slow but is only
3095 // used for reference counts of parameters.
3098 Block::add_statement_at_front(Statement* statement)
3100 this->statements_.insert(this->statements_.begin(), statement);
3103 // Replace a statement in a block.
3106 Block::replace_statement(size_t index, Statement* s)
3108 gcc_assert(index < this->statements_.size());
3109 this->statements_[index] = s;
3112 // Add a statement before another statement.
3115 Block::insert_statement_before(size_t index, Statement* s)
3117 gcc_assert(index < this->statements_.size());
3118 this->statements_.insert(this->statements_.begin() + index, s);
3121 // Add a statement after another statement.
3124 Block::insert_statement_after(size_t index, Statement* s)
3126 gcc_assert(index < this->statements_.size());
3127 this->statements_.insert(this->statements_.begin() + index + 1, s);
3130 // Traverse the tree.
3133 Block::traverse(Traverse* traverse)
3135 unsigned int traverse_mask = traverse->traverse_mask();
3137 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3139 int t = traverse->block(this);
3140 if (t == TRAVERSE_EXIT)
3141 return TRAVERSE_EXIT;
3142 else if (t == TRAVERSE_SKIP_COMPONENTS)
3143 return TRAVERSE_CONTINUE;
3147 & (Traverse::traverse_variables
3148 | Traverse::traverse_constants
3149 | Traverse::traverse_expressions
3150 | Traverse::traverse_types)) != 0)
3152 for (Bindings::const_definitions_iterator pb =
3153 this->bindings_->begin_definitions();
3154 pb != this->bindings_->end_definitions();
3157 switch ((*pb)->classification())
3159 case Named_object::NAMED_OBJECT_CONST:
3160 if ((traverse_mask & Traverse::traverse_constants) != 0)
3162 if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
3163 return TRAVERSE_EXIT;
3165 if ((traverse_mask & Traverse::traverse_types) != 0
3166 || (traverse_mask & Traverse::traverse_expressions) != 0)
3168 Type* t = (*pb)->const_value()->type();
3170 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3171 return TRAVERSE_EXIT;
3173 if ((traverse_mask & Traverse::traverse_expressions) != 0
3174 || (traverse_mask & Traverse::traverse_types) != 0)
3176 if ((*pb)->const_value()->traverse_expression(traverse)
3178 return TRAVERSE_EXIT;
3182 case Named_object::NAMED_OBJECT_VAR:
3183 case Named_object::NAMED_OBJECT_RESULT_VAR:
3184 if ((traverse_mask & Traverse::traverse_variables) != 0)
3186 if (traverse->variable(*pb) == TRAVERSE_EXIT)
3187 return TRAVERSE_EXIT;
3189 if (((traverse_mask & Traverse::traverse_types) != 0
3190 || (traverse_mask & Traverse::traverse_expressions) != 0)
3191 && ((*pb)->is_result_variable()
3192 || (*pb)->var_value()->has_type()))
3194 Type* t = ((*pb)->is_variable()
3195 ? (*pb)->var_value()->type()
3196 : (*pb)->result_var_value()->type());
3198 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3199 return TRAVERSE_EXIT;
3201 if ((*pb)->is_variable()
3202 && ((traverse_mask & Traverse::traverse_expressions) != 0
3203 || (traverse_mask & Traverse::traverse_types) != 0))
3205 if ((*pb)->var_value()->traverse_expression(traverse)
3207 return TRAVERSE_EXIT;
3211 case Named_object::NAMED_OBJECT_FUNC:
3212 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3213 // FIXME: Where will nested functions be found?
3216 case Named_object::NAMED_OBJECT_TYPE:
3217 if ((traverse_mask & Traverse::traverse_types) != 0
3218 || (traverse_mask & Traverse::traverse_expressions) != 0)
3220 if (Type::traverse((*pb)->type_value(), traverse)
3222 return TRAVERSE_EXIT;
3226 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3227 case Named_object::NAMED_OBJECT_UNKNOWN:
3230 case Named_object::NAMED_OBJECT_PACKAGE:
3231 case Named_object::NAMED_OBJECT_SINK:
3240 // No point in checking traverse_mask here--if we got here we always
3241 // want to walk the statements. The traversal can insert new
3242 // statements before or after the current statement. Inserting
3243 // statements before the current statement requires updating I via
3244 // the pointer; those statements will not be traversed. Any new
3245 // statements inserted after the current statement will be traversed
3247 for (size_t i = 0; i < this->statements_.size(); ++i)
3249 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3250 return TRAVERSE_EXIT;
3253 return TRAVERSE_CONTINUE;
3256 // Work out types for unspecified variables and constants.
3259 Block::determine_types()
3261 for (Bindings::const_definitions_iterator pb =
3262 this->bindings_->begin_definitions();
3263 pb != this->bindings_->end_definitions();
3266 if ((*pb)->is_variable())
3267 (*pb)->var_value()->determine_type();
3268 else if ((*pb)->is_const())
3269 (*pb)->const_value()->determine_type();
3272 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3273 ps != this->statements_.end();
3275 (*ps)->determine_types();
3278 // Return true if the statements in this block may fall through.
3281 Block::may_fall_through() const
3283 if (this->statements_.empty())
3285 return this->statements_.back()->may_fall_through();
3290 Variable::Variable(Type* type, Expression* init, bool is_global,
3291 bool is_parameter, bool is_receiver,
3292 source_location location)
3293 : type_(type), init_(init), preinit_(NULL), location_(location),
3294 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3295 is_receiver_(is_receiver), is_varargs_parameter_(false),
3296 is_address_taken_(false), seen_(false), init_is_lowered_(false),
3297 type_from_init_tuple_(false), type_from_range_index_(false),
3298 type_from_range_value_(false), type_from_chan_element_(false),
3299 is_type_switch_var_(false), determined_type_(false)
3301 gcc_assert(type != NULL || init != NULL);
3302 gcc_assert(!is_parameter || init == NULL);
3305 // Traverse the initializer expression.
3308 Variable::traverse_expression(Traverse* traverse)
3310 if (this->preinit_ != NULL)
3312 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3313 return TRAVERSE_EXIT;
3315 if (this->init_ != NULL)
3317 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3318 return TRAVERSE_EXIT;
3320 return TRAVERSE_CONTINUE;
3323 // Lower the initialization expression after parsing is complete.
3326 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3328 if (this->init_ != NULL && !this->init_is_lowered_)
3332 // We will give an error elsewhere, this is just to prevent
3333 // an infinite loop.
3338 gogo->lower_expression(function, &this->init_);
3340 this->seen_ = false;
3342 this->init_is_lowered_ = true;
3346 // Get the preinit block.
3349 Variable::preinit_block(Gogo* gogo)
3351 gcc_assert(this->is_global_);
3352 if (this->preinit_ == NULL)
3353 this->preinit_ = new Block(NULL, this->location());
3355 // If a global variable has a preinitialization statement, then we
3356 // need to have an initialization function.
3357 gogo->set_need_init_fn();
3359 return this->preinit_;
3362 // Add a statement to be run before the initialization expression.
3365 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3367 Block* b = this->preinit_block(gogo);
3368 b->add_statement(s);
3369 b->set_end_location(s->location());
3372 // In an assignment which sets a variable to a tuple of EXPR, return
3373 // the type of the first element of the tuple.
3376 Variable::type_from_tuple(Expression* expr, bool report_error) const
3378 if (expr->map_index_expression() != NULL)
3380 Map_type* mt = expr->map_index_expression()->get_map_type();
3382 return Type::make_error_type();
3383 return mt->val_type();
3385 else if (expr->receive_expression() != NULL)
3387 Expression* channel = expr->receive_expression()->channel();
3388 Type* channel_type = channel->type();
3389 if (channel_type->channel_type() == NULL)
3390 return Type::make_error_type();
3391 return channel_type->channel_type()->element_type();
3396 error_at(this->location(), "invalid tuple definition");
3397 return Type::make_error_type();
3401 // Given EXPR used in a range clause, return either the index type or
3402 // the value type of the range, depending upon GET_INDEX_TYPE.
3405 Variable::type_from_range(Expression* expr, bool get_index_type,
3406 bool report_error) const
3408 Type* t = expr->type();
3409 if (t->array_type() != NULL
3410 || (t->points_to() != NULL
3411 && t->points_to()->array_type() != NULL
3412 && !t->points_to()->is_open_array_type()))
3415 return Type::lookup_integer_type("int");
3417 return t->deref()->array_type()->element_type();
3419 else if (t->is_string_type())
3420 return Type::lookup_integer_type("int");
3421 else if (t->map_type() != NULL)
3424 return t->map_type()->key_type();
3426 return t->map_type()->val_type();
3428 else if (t->channel_type() != NULL)
3431 return t->channel_type()->element_type();
3435 error_at(this->location(),
3436 "invalid definition of value variable for channel range");
3437 return Type::make_error_type();
3443 error_at(this->location(), "invalid type for range clause");
3444 return Type::make_error_type();
3448 // EXPR should be a channel. Return the channel's element type.
3451 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3453 Type* t = expr->type();
3454 if (t->channel_type() != NULL)
3455 return t->channel_type()->element_type();
3459 error_at(this->location(), "expected channel");
3460 return Type::make_error_type();
3464 // Return the type of the Variable. This may be called before
3465 // Variable::determine_type is called, which means that we may need to
3466 // get the type from the initializer. FIXME: If we combine lowering
3467 // with type determination, then this should be unnecessary.
3472 // A variable in a type switch with a nil case will have the wrong
3473 // type here. This gets fixed up in determine_type, below.
3474 Type* type = this->type_;
3475 Expression* init = this->init_;
3476 if (this->is_type_switch_var_
3477 && this->type_->is_nil_constant_as_type())
3479 Type_guard_expression* tge = this->init_->type_guard_expression();
3480 gcc_assert(tge != NULL);
3487 if (this->type_ == NULL || !this->type_->is_error_type())
3489 error_at(this->location_, "variable initializer refers to itself");
3490 this->type_ = Type::make_error_type();
3499 else if (this->type_from_init_tuple_)
3500 type = this->type_from_tuple(init, false);
3501 else if (this->type_from_range_index_ || this->type_from_range_value_)
3502 type = this->type_from_range(init, this->type_from_range_index_, false);
3503 else if (this->type_from_chan_element_)
3504 type = this->type_from_chan_element(init, false);
3507 gcc_assert(init != NULL);
3508 type = init->type();
3509 gcc_assert(type != NULL);
3511 // Variables should not have abstract types.
3512 if (type->is_abstract())
3513 type = type->make_non_abstract_type();
3515 if (type->is_void_type())
3516 type = Type::make_error_type();
3519 this->seen_ = false;
3524 // Fetch the type from a const pointer, in which case it should have
3525 // been set already.
3528 Variable::type() const
3530 gcc_assert(this->type_ != NULL);
3534 // Set the type if necessary.
3537 Variable::determine_type()
3539 if (this->determined_type_)
3541 this->determined_type_ = true;
3543 if (this->preinit_ != NULL)
3544 this->preinit_->determine_types();
3546 // A variable in a type switch with a nil case will have the wrong
3547 // type here. It will have an initializer which is a type guard.
3548 // We want to initialize it to the value without the type guard, and
3549 // use the type of that value as well.
3550 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3552 Type_guard_expression* tge = this->init_->type_guard_expression();
3553 gcc_assert(tge != NULL);
3555 this->init_ = tge->expr();
3558 if (this->init_ == NULL)
3559 gcc_assert(this->type_ != NULL && !this->type_->is_abstract());
3560 else if (this->type_from_init_tuple_)
3562 Expression *init = this->init_;
3563 init->determine_type_no_context();
3564 this->type_ = this->type_from_tuple(init, true);
3567 else if (this->type_from_range_index_ || this->type_from_range_value_)
3569 Expression* init = this->init_;
3570 init->determine_type_no_context();
3571 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3575 else if (this->type_from_chan_element_)
3577 Expression* init = this->init_;
3578 init->determine_type_no_context();
3579 this->type_ = this->type_from_chan_element(init, true);
3584 Type_context context(this->type_, false);
3585 this->init_->determine_type(&context);
3586 if (this->type_ == NULL)
3588 Type* type = this->init_->type();
3589 gcc_assert(type != NULL);
3590 if (type->is_abstract())
3591 type = type->make_non_abstract_type();
3593 if (type->is_void_type())
3595 error_at(this->location_, "variable has no type");
3596 type = Type::make_error_type();
3598 else if (type->is_nil_type())
3600 error_at(this->location_, "variable defined to nil type");
3601 type = Type::make_error_type();
3603 else if (type->is_call_multiple_result_type())
3605 error_at(this->location_,
3606 "single variable set to multiple value function call");
3607 type = Type::make_error_type();
3615 // Export the variable
3618 Variable::export_var(Export* exp, const std::string& name) const
3620 gcc_assert(this->is_global_);
3621 exp->write_c_string("var ");
3622 exp->write_string(name);
3623 exp->write_c_string(" ");
3624 exp->write_type(this->type());
3625 exp->write_c_string(";\n");
3628 // Import a variable.
3631 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3633 imp->require_c_string("var ");
3634 *pname = imp->read_identifier();
3635 imp->require_c_string(" ");
3636 *ptype = imp->read_type();
3637 imp->require_c_string(";\n");
3640 // Convert a variable to the backend representation.
3643 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
3644 const Package* package, const std::string& name)
3646 if (this->backend_ == NULL)
3648 Backend* backend = gogo->backend();
3649 Type* type = this->type_;
3650 if (type->is_error_type()
3651 || (type->is_undefined()
3652 && (!this->is_global_ || package == NULL)))
3653 this->backend_ = backend->error_variable();
3656 bool is_parameter = this->is_parameter_;
3657 if (this->is_receiver_ && type->points_to() == NULL)
3658 is_parameter = false;
3659 if (this->is_in_heap())
3661 is_parameter = false;
3662 type = Type::make_pointer_type(type);
3665 std::string n = Gogo::unpack_hidden_name(name);
3666 Btype* btype = tree_to_type(type->get_tree(gogo));
3669 if (this->is_global_)
3670 bvar = backend->global_variable((package == NULL
3671 ? gogo->package_name()
3674 ? gogo->unique_prefix()
3675 : package->unique_prefix()),
3679 Gogo::is_hidden_name(name),
3683 tree fndecl = function->func_value()->get_decl();
3684 Bfunction* bfunction = tree_to_function(fndecl);
3686 bvar = backend->parameter_variable(bfunction, n, btype,
3689 bvar = backend->local_variable(bfunction, n, btype,
3692 this->backend_ = bvar;
3695 return this->backend_;
3698 // Class Result_variable.
3700 // Convert a result variable to the backend representation.
3703 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
3704 const std::string& name)
3706 if (this->backend_ == NULL)
3708 Backend* backend = gogo->backend();
3709 Type* type = this->type_;
3710 if (type->is_error())
3711 this->backend_ = backend->error_variable();
3714 if (this->is_in_heap())
3715 type = Type::make_pointer_type(type);
3716 Btype* btype = tree_to_type(type->get_tree(gogo));
3717 tree fndecl = function->func_value()->get_decl();
3718 Bfunction* bfunction = tree_to_function(fndecl);
3719 std::string n = Gogo::unpack_hidden_name(name);
3720 this->backend_ = backend->local_variable(bfunction, n, btype,
3724 return this->backend_;
3727 // Class Named_constant.
3729 // Traverse the initializer expression.
3732 Named_constant::traverse_expression(Traverse* traverse)
3734 return Expression::traverse(&this->expr_, traverse);
3737 // Determine the type of the constant.
3740 Named_constant::determine_type()
3742 if (this->type_ != NULL)
3744 Type_context context(this->type_, false);
3745 this->expr_->determine_type(&context);
3749 // A constant may have an abstract type.
3750 Type_context context(NULL, true);
3751 this->expr_->determine_type(&context);
3752 this->type_ = this->expr_->type();
3753 gcc_assert(this->type_ != NULL);
3757 // Indicate that we found and reported an error for this constant.
3760 Named_constant::set_error()
3762 this->type_ = Type::make_error_type();
3763 this->expr_ = Expression::make_error(this->location_);
3766 // Export a constant.
3769 Named_constant::export_const(Export* exp, const std::string& name) const
3771 exp->write_c_string("const ");
3772 exp->write_string(name);
3773 exp->write_c_string(" ");
3774 if (!this->type_->is_abstract())
3776 exp->write_type(this->type_);
3777 exp->write_c_string(" ");
3779 exp->write_c_string("= ");
3780 this->expr()->export_expression(exp);
3781 exp->write_c_string(";\n");
3784 // Import a constant.
3787 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3790 imp->require_c_string("const ");
3791 *pname = imp->read_identifier();
3792 imp->require_c_string(" ");
3793 if (imp->peek_char() == '=')
3797 *ptype = imp->read_type();
3798 imp->require_c_string(" ");
3800 imp->require_c_string("= ");
3801 *pexpr = Expression::import_expression(imp);
3802 imp->require_c_string(";\n");
3808 Type_declaration::add_method(const std::string& name, Function* function)
3810 Named_object* ret = Named_object::make_function(name, NULL, function);
3811 this->methods_.push_back(ret);
3815 // Add a method declaration.
3818 Type_declaration::add_method_declaration(const std::string& name,
3819 Function_type* type,
3820 source_location location)
3822 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3824 this->methods_.push_back(ret);
3828 // Return whether any methods ere defined.
3831 Type_declaration::has_methods() const
3833 return !this->methods_.empty();
3836 // Define methods for the real type.
3839 Type_declaration::define_methods(Named_type* nt)
3841 for (Methods::const_iterator p = this->methods_.begin();
3842 p != this->methods_.end();
3844 nt->add_existing_method(*p);
3847 // We are using the type. Return true if we should issue a warning.
3850 Type_declaration::using_type()
3852 bool ret = !this->issued_warning_;
3853 this->issued_warning_ = true;
3857 // Class Unknown_name.
3859 // Set the real named object.
3862 Unknown_name::set_real_named_object(Named_object* no)
3864 gcc_assert(this->real_named_object_ == NULL);
3865 gcc_assert(!no->is_unknown());
3866 this->real_named_object_ = no;
3869 // Class Named_object.
3871 Named_object::Named_object(const std::string& name,
3872 const Package* package,
3873 Classification classification)
3874 : name_(name), package_(package), classification_(classification),
3877 if (Gogo::is_sink_name(name))
3878 gcc_assert(classification == NAMED_OBJECT_SINK);
3881 // Make an unknown name. This is used by the parser. The name must
3882 // be resolved later. Unknown names are only added in the current
3886 Named_object::make_unknown_name(const std::string& name,
3887 source_location location)
3889 Named_object* named_object = new Named_object(name, NULL,
3890 NAMED_OBJECT_UNKNOWN);
3891 Unknown_name* value = new Unknown_name(location);
3892 named_object->u_.unknown_value = value;
3893 return named_object;
3899 Named_object::make_constant(const Typed_identifier& tid,
3900 const Package* package, Expression* expr,
3903 Named_object* named_object = new Named_object(tid.name(), package,
3904 NAMED_OBJECT_CONST);
3905 Named_constant* named_constant = new Named_constant(tid.type(), expr,
3908 named_object->u_.const_value = named_constant;
3909 return named_object;
3912 // Make a named type.
3915 Named_object::make_type(const std::string& name, const Package* package,
3916 Type* type, source_location location)
3918 Named_object* named_object = new Named_object(name, package,
3920 Named_type* named_type = Type::make_named_type(named_object, type, location);
3921 named_object->u_.type_value = named_type;
3922 return named_object;
3925 // Make a type declaration.
3928 Named_object::make_type_declaration(const std::string& name,
3929 const Package* package,
3930 source_location location)
3932 Named_object* named_object = new Named_object(name, package,
3933 NAMED_OBJECT_TYPE_DECLARATION);
3934 Type_declaration* type_declaration = new Type_declaration(location);
3935 named_object->u_.type_declaration = type_declaration;
3936 return named_object;
3942 Named_object::make_variable(const std::string& name, const Package* package,
3945 Named_object* named_object = new Named_object(name, package,
3947 named_object->u_.var_value = variable;
3948 return named_object;
3951 // Make a result variable.
3954 Named_object::make_result_variable(const std::string& name,
3955 Result_variable* result)
3957 Named_object* named_object = new Named_object(name, NULL,
3958 NAMED_OBJECT_RESULT_VAR);
3959 named_object->u_.result_var_value = result;
3960 return named_object;
3963 // Make a sink. This is used for the special blank identifier _.
3966 Named_object::make_sink()
3968 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
3971 // Make a named function.
3974 Named_object::make_function(const std::string& name, const Package* package,
3977 Named_object* named_object = new Named_object(name, package,
3979 named_object->u_.func_value = function;
3980 return named_object;
3983 // Make a function declaration.
3986 Named_object::make_function_declaration(const std::string& name,
3987 const Package* package,
3988 Function_type* fntype,
3989 source_location location)
3991 Named_object* named_object = new Named_object(name, package,
3992 NAMED_OBJECT_FUNC_DECLARATION);
3993 Function_declaration *func_decl = new Function_declaration(fntype, location);
3994 named_object->u_.func_declaration_value = func_decl;
3995 return named_object;
4001 Named_object::make_package(const std::string& alias, Package* package)
4003 Named_object* named_object = new Named_object(alias, NULL,
4004 NAMED_OBJECT_PACKAGE);
4005 named_object->u_.package_value = package;
4006 return named_object;
4009 // Return the name to use in an error message.
4012 Named_object::message_name() const
4014 if (this->package_ == NULL)
4015 return Gogo::message_name(this->name_);
4016 std::string ret = Gogo::message_name(this->package_->name());
4018 ret += Gogo::message_name(this->name_);
4022 // Set the type when a declaration is defined.
4025 Named_object::set_type_value(Named_type* named_type)
4027 gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4028 Type_declaration* td = this->u_.type_declaration;
4029 td->define_methods(named_type);
4030 Named_object* in_function = td->in_function();
4031 if (in_function != NULL)
4032 named_type->set_in_function(in_function);
4034 this->classification_ = NAMED_OBJECT_TYPE;
4035 this->u_.type_value = named_type;
4038 // Define a function which was previously declared.
4041 Named_object::set_function_value(Function* function)
4043 gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4044 this->classification_ = NAMED_OBJECT_FUNC;
4045 // FIXME: We should free the old value.
4046 this->u_.func_value = function;
4049 // Declare an unknown object as a type declaration.
4052 Named_object::declare_as_type()
4054 gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4055 Unknown_name* unk = this->u_.unknown_value;
4056 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
4057 this->u_.type_declaration = new Type_declaration(unk->location());
4061 // Return the location of a named object.
4064 Named_object::location() const
4066 switch (this->classification_)
4069 case NAMED_OBJECT_UNINITIALIZED:
4072 case NAMED_OBJECT_UNKNOWN:
4073 return this->unknown_value()->location();
4075 case NAMED_OBJECT_CONST:
4076 return this->const_value()->location();
4078 case NAMED_OBJECT_TYPE:
4079 return this->type_value()->location();
4081 case NAMED_OBJECT_TYPE_DECLARATION:
4082 return this->type_declaration_value()->location();
4084 case NAMED_OBJECT_VAR:
4085 return this->var_value()->location();
4087 case NAMED_OBJECT_RESULT_VAR:
4088 return this->result_var_value()->location();
4090 case NAMED_OBJECT_SINK:
4093 case NAMED_OBJECT_FUNC:
4094 return this->func_value()->location();
4096 case NAMED_OBJECT_FUNC_DECLARATION:
4097 return this->func_declaration_value()->location();
4099 case NAMED_OBJECT_PACKAGE:
4100 return this->package_value()->location();
4104 // Export a named object.
4107 Named_object::export_named_object(Export* exp) const
4109 switch (this->classification_)
4112 case NAMED_OBJECT_UNINITIALIZED:
4113 case NAMED_OBJECT_UNKNOWN:
4116 case NAMED_OBJECT_CONST:
4117 this->const_value()->export_const(exp, this->name_);
4120 case NAMED_OBJECT_TYPE:
4121 this->type_value()->export_named_type(exp, this->name_);
4124 case NAMED_OBJECT_TYPE_DECLARATION:
4125 error_at(this->type_declaration_value()->location(),
4126 "attempt to export %<%s%> which was declared but not defined",
4127 this->message_name().c_str());
4130 case NAMED_OBJECT_FUNC_DECLARATION:
4131 this->func_declaration_value()->export_func(exp, this->name_);
4134 case NAMED_OBJECT_VAR:
4135 this->var_value()->export_var(exp, this->name_);
4138 case NAMED_OBJECT_RESULT_VAR:
4139 case NAMED_OBJECT_SINK:
4142 case NAMED_OBJECT_FUNC:
4143 this->func_value()->export_func(exp, this->name_);
4148 // Convert a variable to the backend representation.
4151 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
4153 if (this->classification_ == NAMED_OBJECT_VAR)
4154 return this->var_value()->get_backend_variable(gogo, function,
4155 this->package_, this->name_);
4156 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
4157 return this->result_var_value()->get_backend_variable(gogo, function,
4165 Bindings::Bindings(Bindings* enclosing)
4166 : enclosing_(enclosing), named_objects_(), bindings_()
4173 Bindings::clear_file_scope()
4175 Contour::iterator p = this->bindings_.begin();
4176 while (p != this->bindings_.end())
4179 if (p->second->package() != NULL)
4181 else if (p->second->is_package())
4183 else if (p->second->is_function()
4184 && !p->second->func_value()->type()->is_method()
4185 && Gogo::unpack_hidden_name(p->second->name()) == "init")
4193 p = this->bindings_.erase(p);
4197 // Look up a symbol.
4200 Bindings::lookup(const std::string& name) const
4202 Contour::const_iterator p = this->bindings_.find(name);
4203 if (p != this->bindings_.end())
4204 return p->second->resolve();
4205 else if (this->enclosing_ != NULL)
4206 return this->enclosing_->lookup(name);
4211 // Look up a symbol locally.
4214 Bindings::lookup_local(const std::string& name) const
4216 Contour::const_iterator p = this->bindings_.find(name);
4217 if (p == this->bindings_.end())
4222 // Remove an object from a set of bindings. This is used for a
4223 // special case in thunks for functions which call recover.
4226 Bindings::remove_binding(Named_object* no)
4228 Contour::iterator pb = this->bindings_.find(no->name());
4229 gcc_assert(pb != this->bindings_.end());
4230 this->bindings_.erase(pb);
4231 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4232 pn != this->named_objects_.end();
4237 this->named_objects_.erase(pn);
4244 // Add a method to the list of objects. This is not added to the
4245 // lookup table. This is so that we have a single list of objects
4246 // declared at the top level, which we walk through when it's time to
4247 // convert to trees.
4250 Bindings::add_method(Named_object* method)
4252 this->named_objects_.push_back(method);
4255 // Add a generic Named_object to a Contour.
4258 Bindings::add_named_object_to_contour(Contour* contour,
4259 Named_object* named_object)
4261 gcc_assert(named_object == named_object->resolve());
4262 const std::string& name(named_object->name());
4263 gcc_assert(!Gogo::is_sink_name(name));
4265 std::pair<Contour::iterator, bool> ins =
4266 contour->insert(std::make_pair(name, named_object));
4269 // The name was already there.
4270 if (named_object->package() != NULL
4271 && ins.first->second->package() == named_object->package()
4272 && (ins.first->second->classification()
4273 == named_object->classification()))
4275 // This is a second import of the same object.
4276 return ins.first->second;
4278 ins.first->second = this->new_definition(ins.first->second,
4280 return ins.first->second;
4284 // Don't push declarations on the list. We push them on when
4285 // and if we find the definitions. That way we genericize the
4286 // functions in order.
4287 if (!named_object->is_type_declaration()
4288 && !named_object->is_function_declaration()
4289 && !named_object->is_unknown())
4290 this->named_objects_.push_back(named_object);
4291 return named_object;
4295 // We had an existing named object OLD_OBJECT, and we've seen a new
4296 // one NEW_OBJECT with the same name. FIXME: This does not free the
4297 // new object when we don't need it.
4300 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4303 switch (old_object->classification())
4306 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4309 case Named_object::NAMED_OBJECT_UNKNOWN:
4311 Named_object* real = old_object->unknown_value()->real_named_object();
4313 return this->new_definition(real, new_object);
4314 gcc_assert(!new_object->is_unknown());
4315 old_object->unknown_value()->set_real_named_object(new_object);
4316 if (!new_object->is_type_declaration()
4317 && !new_object->is_function_declaration())
4318 this->named_objects_.push_back(new_object);
4322 case Named_object::NAMED_OBJECT_CONST:
4325 case Named_object::NAMED_OBJECT_TYPE:
4326 if (new_object->is_type_declaration())
4330 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4331 if (new_object->is_type_declaration())
4333 if (new_object->is_type())
4335 old_object->set_type_value(new_object->type_value());
4336 new_object->type_value()->set_named_object(old_object);
4337 this->named_objects_.push_back(old_object);
4342 case Named_object::NAMED_OBJECT_VAR:
4343 case Named_object::NAMED_OBJECT_RESULT_VAR:
4346 case Named_object::NAMED_OBJECT_SINK:
4349 case Named_object::NAMED_OBJECT_FUNC:
4350 if (new_object->is_function_declaration())
4352 if (!new_object->func_declaration_value()->asm_name().empty())
4353 sorry("__asm__ for function definitions");
4354 Function_type* old_type = old_object->func_value()->type();
4355 Function_type* new_type =
4356 new_object->func_declaration_value()->type();
4357 if (old_type->is_valid_redeclaration(new_type, &reason))
4362 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4364 Function_type* old_type = old_object->func_declaration_value()->type();
4365 if (new_object->is_function_declaration())
4367 Function_type* new_type =
4368 new_object->func_declaration_value()->type();
4369 if (old_type->is_valid_redeclaration(new_type, &reason))
4372 if (new_object->is_function())
4374 Function_type* new_type = new_object->func_value()->type();
4375 if (old_type->is_valid_redeclaration(new_type, &reason))
4377 if (!old_object->func_declaration_value()->asm_name().empty())
4378 sorry("__asm__ for function definitions");
4379 old_object->set_function_value(new_object->func_value());
4380 this->named_objects_.push_back(old_object);
4387 case Named_object::NAMED_OBJECT_PACKAGE:
4388 if (new_object->is_package()
4389 && (old_object->package_value()->name()
4390 == new_object->package_value()->name()))
4396 std::string n = old_object->message_name();
4398 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4400 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4403 inform(old_object->location(), "previous definition of %qs was here",
4409 // Add a named type.
4412 Bindings::add_named_type(Named_type* named_type)
4414 return this->add_named_object(named_type->named_object());
4420 Bindings::add_function(const std::string& name, const Package* package,
4423 return this->add_named_object(Named_object::make_function(name, package,
4427 // Add a function declaration.
4430 Bindings::add_function_declaration(const std::string& name,
4431 const Package* package,
4432 Function_type* type,
4433 source_location location)
4435 Named_object* no = Named_object::make_function_declaration(name, package,
4437 return this->add_named_object(no);
4440 // Define a type which was previously declared.
4443 Bindings::define_type(Named_object* no, Named_type* type)
4445 no->set_type_value(type);
4446 this->named_objects_.push_back(no);
4449 // Traverse bindings.
4452 Bindings::traverse(Traverse* traverse, bool is_global)
4454 unsigned int traverse_mask = traverse->traverse_mask();
4456 // We don't use an iterator because we permit the traversal to add
4457 // new global objects.
4458 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4460 Named_object* p = this->named_objects_[i];
4461 switch (p->classification())
4463 case Named_object::NAMED_OBJECT_CONST:
4464 if ((traverse_mask & Traverse::traverse_constants) != 0)
4466 if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4467 return TRAVERSE_EXIT;
4469 if ((traverse_mask & Traverse::traverse_types) != 0
4470 || (traverse_mask & Traverse::traverse_expressions) != 0)
4472 Type* t = p->const_value()->type();
4474 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4475 return TRAVERSE_EXIT;
4476 if (p->const_value()->traverse_expression(traverse)
4478 return TRAVERSE_EXIT;
4482 case Named_object::NAMED_OBJECT_VAR:
4483 case Named_object::NAMED_OBJECT_RESULT_VAR:
4484 if ((traverse_mask & Traverse::traverse_variables) != 0)
4486 if (traverse->variable(p) == TRAVERSE_EXIT)
4487 return TRAVERSE_EXIT;
4489 if (((traverse_mask & Traverse::traverse_types) != 0
4490 || (traverse_mask & Traverse::traverse_expressions) != 0)
4491 && (p->is_result_variable()
4492 || p->var_value()->has_type()))
4494 Type* t = (p->is_variable()
4495 ? p->var_value()->type()
4496 : p->result_var_value()->type());
4498 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4499 return TRAVERSE_EXIT;
4501 if (p->is_variable()
4502 && ((traverse_mask & Traverse::traverse_types) != 0
4503 || (traverse_mask & Traverse::traverse_expressions) != 0))
4505 if (p->var_value()->traverse_expression(traverse)
4507 return TRAVERSE_EXIT;
4511 case Named_object::NAMED_OBJECT_FUNC:
4512 if ((traverse_mask & Traverse::traverse_functions) != 0)
4514 int t = traverse->function(p);
4515 if (t == TRAVERSE_EXIT)
4516 return TRAVERSE_EXIT;
4517 else if (t == TRAVERSE_SKIP_COMPONENTS)
4522 & (Traverse::traverse_variables
4523 | Traverse::traverse_constants
4524 | Traverse::traverse_functions
4525 | Traverse::traverse_blocks
4526 | Traverse::traverse_statements
4527 | Traverse::traverse_expressions
4528 | Traverse::traverse_types)) != 0)
4530 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4531 return TRAVERSE_EXIT;
4535 case Named_object::NAMED_OBJECT_PACKAGE:
4536 // These are traversed in Gogo::traverse.
4537 gcc_assert(is_global);
4540 case Named_object::NAMED_OBJECT_TYPE:
4541 if ((traverse_mask & Traverse::traverse_types) != 0
4542 || (traverse_mask & Traverse::traverse_expressions) != 0)
4544 if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4545 return TRAVERSE_EXIT;
4549 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4550 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4551 case Named_object::NAMED_OBJECT_UNKNOWN:
4554 case Named_object::NAMED_OBJECT_SINK:
4560 return TRAVERSE_CONTINUE;
4565 // Get the backend representation for a label.
4568 Label::get_backend_label(Translate_context* context)
4570 if (this->blabel_ == NULL)
4572 Function* function = context->function()->func_value();
4573 tree fndecl = function->get_decl();
4574 Bfunction* bfunction = tree_to_function(fndecl);
4575 this->blabel_ = context->backend()->label(bfunction, this->name_,
4578 return this->blabel_;
4581 // Return an expression for the address of this label.
4584 Label::get_addr(Translate_context* context, source_location location)
4586 Blabel* label = this->get_backend_label(context);
4587 return context->backend()->label_address(label, location);
4590 // Class Unnamed_label.
4592 // Get the backend representation for an unnamed label.
4595 Unnamed_label::get_blabel(Translate_context* context)
4597 if (this->blabel_ == NULL)
4599 Function* function = context->function()->func_value();
4600 tree fndecl = function->get_decl();
4601 Bfunction* bfunction = tree_to_function(fndecl);
4602 this->blabel_ = context->backend()->label(bfunction, "",
4605 return this->blabel_;
4608 // Return a statement which defines this unnamed label.
4611 Unnamed_label::get_definition(Translate_context* context)
4613 Blabel* blabel = this->get_blabel(context);
4614 return context->backend()->label_definition_statement(blabel);
4617 // Return a goto statement to this unnamed label.
4620 Unnamed_label::get_goto(Translate_context* context, source_location location)
4622 Blabel* blabel = this->get_blabel(context);
4623 return context->backend()->goto_statement(blabel, location);
4628 Package::Package(const std::string& name, const std::string& unique_prefix,
4629 source_location location)
4630 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4631 priority_(0), location_(location), used_(false), is_imported_(false),
4632 uses_sink_alias_(false)
4634 gcc_assert(!name.empty() && !unique_prefix.empty());
4637 // Set the priority. We may see multiple priorities for an imported
4638 // package; we want to use the largest one.
4641 Package::set_priority(int priority)
4643 if (priority > this->priority_)
4644 this->priority_ = priority;
4647 // Determine types of constants. Everything else in a package
4648 // (variables, function declarations) should already have a fixed
4649 // type. Constants may have abstract types.
4652 Package::determine_types()
4654 Bindings* bindings = this->bindings_;
4655 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4656 p != bindings->end_definitions();
4659 if ((*p)->is_const())
4660 (*p)->const_value()->determine_type();
4668 Traverse::~Traverse()
4670 if (this->types_seen_ != NULL)
4671 delete this->types_seen_;
4672 if (this->expressions_seen_ != NULL)
4673 delete this->expressions_seen_;
4676 // Record that we are looking at a type, and return true if we have
4680 Traverse::remember_type(const Type* type)
4682 if (type->is_error_type())
4684 gcc_assert((this->traverse_mask() & traverse_types) != 0
4685 || (this->traverse_mask() & traverse_expressions) != 0);
4686 // We only have to remember named types, as they are the only ones
4687 // we can see multiple times in a traversal.
4688 if (type->classification() != Type::TYPE_NAMED)
4690 if (this->types_seen_ == NULL)
4691 this->types_seen_ = new Types_seen();
4692 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4696 // Record that we are looking at an expression, and return true if we
4697 // have already seen it.
4700 Traverse::remember_expression(const Expression* expression)
4702 gcc_assert((this->traverse_mask() & traverse_types) != 0
4703 || (this->traverse_mask() & traverse_expressions) != 0);
4704 if (this->expressions_seen_ == NULL)
4705 this->expressions_seen_ = new Expressions_seen();
4706 std::pair<Expressions_seen::iterator, bool> ins =
4707 this->expressions_seen_->insert(expression);
4711 // The default versions of these functions should never be called: the
4712 // traversal mask indicates which functions may be called.
4715 Traverse::variable(Named_object*)
4721 Traverse::constant(Named_object*, bool)
4727 Traverse::function(Named_object*)
4733 Traverse::block(Block*)
4739 Traverse::statement(Block*, size_t*, Statement*)
4745 Traverse::expression(Expression**)
4751 Traverse::type(Type*)