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),
37 unique_prefix_specified_(false),
39 named_types_are_converted_(false)
41 const source_location loc = BUILTINS_LOCATION;
43 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
44 RUNTIME_TYPE_KIND_UINT8);
45 this->add_named_type(uint8_type);
46 this->add_named_type(Type::make_integer_type("uint16", true, 16,
47 RUNTIME_TYPE_KIND_UINT16));
48 this->add_named_type(Type::make_integer_type("uint32", true, 32,
49 RUNTIME_TYPE_KIND_UINT32));
50 this->add_named_type(Type::make_integer_type("uint64", true, 64,
51 RUNTIME_TYPE_KIND_UINT64));
53 this->add_named_type(Type::make_integer_type("int8", false, 8,
54 RUNTIME_TYPE_KIND_INT8));
55 this->add_named_type(Type::make_integer_type("int16", false, 16,
56 RUNTIME_TYPE_KIND_INT16));
57 this->add_named_type(Type::make_integer_type("int32", false, 32,
58 RUNTIME_TYPE_KIND_INT32));
59 this->add_named_type(Type::make_integer_type("int64", false, 64,
60 RUNTIME_TYPE_KIND_INT64));
62 this->add_named_type(Type::make_float_type("float32", 32,
63 RUNTIME_TYPE_KIND_FLOAT32));
64 this->add_named_type(Type::make_float_type("float64", 64,
65 RUNTIME_TYPE_KIND_FLOAT64));
67 this->add_named_type(Type::make_complex_type("complex64", 64,
68 RUNTIME_TYPE_KIND_COMPLEX64));
69 this->add_named_type(Type::make_complex_type("complex128", 128,
70 RUNTIME_TYPE_KIND_COMPLEX128));
72 if (int_type_size < 32)
74 this->add_named_type(Type::make_integer_type("uint", true,
76 RUNTIME_TYPE_KIND_UINT));
77 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
78 RUNTIME_TYPE_KIND_INT);
79 this->add_named_type(int_type);
81 // "byte" is an alias for "uint8". Construct a Named_object which
82 // points to UINT8_TYPE. Note that this breaks the normal pairing
83 // in which a Named_object points to a Named_type which points back
84 // to the same Named_object.
85 Named_object* byte_type = this->declare_type("byte", loc);
86 byte_type->set_type_value(uint8_type);
88 // "rune" is an alias for "int".
89 Named_object* rune_type = this->declare_type("rune", loc);
90 rune_type->set_type_value(int_type);
92 this->add_named_type(Type::make_integer_type("uintptr", true,
94 RUNTIME_TYPE_KIND_UINTPTR));
96 this->add_named_type(Type::make_named_bool_type());
98 this->add_named_type(Type::make_named_string_type());
100 // "error" is interface { Error() string }.
102 Typed_identifier_list *methods = new Typed_identifier_list;
103 Typed_identifier_list *results = new Typed_identifier_list;
104 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
105 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
106 methods->push_back(Typed_identifier("Error", method_type, loc));
107 Type *error_iface = Type::make_interface_type(methods, loc);
108 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
109 this->add_named_type(error_type);
112 this->globals_->add_constant(Typed_identifier("true",
113 Type::make_boolean_type(),
116 Expression::make_boolean(true, loc),
118 this->globals_->add_constant(Typed_identifier("false",
119 Type::make_boolean_type(),
122 Expression::make_boolean(false, loc),
125 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
128 Expression::make_nil(loc),
131 Type* abstract_int_type = Type::make_abstract_integer_type();
132 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
135 Expression::make_iota(),
138 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
139 new_type->set_is_varargs();
140 new_type->set_is_builtin();
141 this->globals_->add_function_declaration("new", NULL, new_type, loc);
143 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
144 make_type->set_is_varargs();
145 make_type->set_is_builtin();
146 this->globals_->add_function_declaration("make", NULL, make_type, loc);
148 Typed_identifier_list* len_result = new Typed_identifier_list();
149 len_result->push_back(Typed_identifier("", int_type, loc));
150 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
152 len_type->set_is_builtin();
153 this->globals_->add_function_declaration("len", NULL, len_type, loc);
155 Typed_identifier_list* cap_result = new Typed_identifier_list();
156 cap_result->push_back(Typed_identifier("", int_type, loc));
157 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
159 cap_type->set_is_builtin();
160 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
162 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
163 print_type->set_is_varargs();
164 print_type->set_is_builtin();
165 this->globals_->add_function_declaration("print", NULL, print_type, loc);
167 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
168 print_type->set_is_varargs();
169 print_type->set_is_builtin();
170 this->globals_->add_function_declaration("println", NULL, print_type, loc);
172 Type *empty = Type::make_interface_type(NULL, loc);
173 Typed_identifier_list* panic_parms = new Typed_identifier_list();
174 panic_parms->push_back(Typed_identifier("e", empty, loc));
175 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
177 panic_type->set_is_builtin();
178 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
180 Typed_identifier_list* recover_result = new Typed_identifier_list();
181 recover_result->push_back(Typed_identifier("", empty, loc));
182 Function_type* recover_type = Type::make_function_type(NULL, NULL,
185 recover_type->set_is_builtin();
186 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
188 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
189 close_type->set_is_varargs();
190 close_type->set_is_builtin();
191 this->globals_->add_function_declaration("close", NULL, close_type, loc);
193 Typed_identifier_list* copy_result = new Typed_identifier_list();
194 copy_result->push_back(Typed_identifier("", int_type, loc));
195 Function_type* copy_type = Type::make_function_type(NULL, NULL,
197 copy_type->set_is_varargs();
198 copy_type->set_is_builtin();
199 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
201 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
202 append_type->set_is_varargs();
203 append_type->set_is_builtin();
204 this->globals_->add_function_declaration("append", NULL, append_type, loc);
206 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
207 complex_type->set_is_varargs();
208 complex_type->set_is_builtin();
209 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
211 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
212 real_type->set_is_varargs();
213 real_type->set_is_builtin();
214 this->globals_->add_function_declaration("real", NULL, real_type, loc);
216 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
217 imag_type->set_is_varargs();
218 imag_type->set_is_builtin();
219 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
221 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
222 delete_type->set_is_varargs();
223 delete_type->set_is_builtin();
224 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
227 // Munge name for use in an error message.
230 Gogo::message_name(const std::string& name)
232 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
235 // Get the package name.
238 Gogo::package_name() const
240 go_assert(this->package_ != NULL);
241 return this->package_->name();
244 // Set the package name.
247 Gogo::set_package_name(const std::string& package_name,
248 source_location location)
250 if (this->package_ != NULL && this->package_->name() != package_name)
252 error_at(location, "expected package %<%s%>",
253 Gogo::message_name(this->package_->name()).c_str());
257 // If the user did not specify a unique prefix, we always use "go".
258 // This in effect requires that the package name be unique.
259 if (this->unique_prefix_.empty())
260 this->unique_prefix_ = "go";
262 this->package_ = this->register_package(package_name, this->unique_prefix_,
265 // We used to permit people to qualify symbols with the current
266 // package name (e.g., P.x), but we no longer do.
267 // this->globals_->add_package(package_name, this->package_);
269 if (this->is_main_package())
271 // Declare "main" as a function which takes no parameters and
273 this->declare_function("main",
274 Type::make_function_type(NULL, NULL, NULL,
280 // Return whether this is the "main" package. This is not true if
281 // -fgo-prefix was used.
284 Gogo::is_main_package() const
286 return this->package_name() == "main" && !this->unique_prefix_specified_;
292 Gogo::import_package(const std::string& filename,
293 const std::string& local_name,
294 bool is_local_name_exported,
295 source_location location)
297 if (filename == "unsafe")
299 this->import_unsafe(local_name, is_local_name_exported, location);
303 Imports::const_iterator p = this->imports_.find(filename);
304 if (p != this->imports_.end())
306 Package* package = p->second;
307 package->set_location(location);
308 package->set_is_imported();
309 std::string ln = local_name;
310 bool is_ln_exported = is_local_name_exported;
313 ln = package->name();
314 is_ln_exported = Lex::is_exported_name(ln);
318 Bindings* bindings = package->bindings();
319 for (Bindings::const_declarations_iterator p =
320 bindings->begin_declarations();
321 p != bindings->end_declarations();
323 this->add_named_object(p->second);
326 package->set_uses_sink_alias();
329 ln = this->pack_hidden_name(ln, is_ln_exported);
330 this->package_->bindings()->add_package(ln, package);
335 Import::Stream* stream = Import::open_package(filename, location);
338 error_at(location, "import file %qs not found", filename.c_str());
342 Import imp(stream, location);
343 imp.register_builtin_types(this);
344 Package* package = imp.import(this, local_name, is_local_name_exported);
347 if (package->name() == this->package_name()
348 && package->unique_prefix() == this->unique_prefix())
350 ("imported package uses same package name and prefix "
351 "as package being compiled (see -fgo-prefix option)"));
353 this->imports_.insert(std::make_pair(filename, package));
354 package->set_is_imported();
360 // Add an import control function for an imported package to the list.
363 Gogo::add_import_init_fn(const std::string& package_name,
364 const std::string& init_name, int prio)
366 for (std::set<Import_init>::const_iterator p =
367 this->imported_init_fns_.begin();
368 p != this->imported_init_fns_.end();
371 if (p->init_name() == init_name
372 && (p->package_name() != package_name || p->priority() != prio))
374 error("duplicate package initialization name %qs",
375 Gogo::message_name(init_name).c_str());
376 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
377 Gogo::message_name(p->package_name()).c_str(),
379 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
380 Gogo::message_name(package_name).c_str(), prio);
385 this->imported_init_fns_.insert(Import_init(package_name, init_name,
389 // Return whether we are at the global binding level.
392 Gogo::in_global_scope() const
394 return this->functions_.empty();
397 // Return the current binding contour.
400 Gogo::current_bindings()
402 if (!this->functions_.empty())
403 return this->functions_.back().blocks.back()->bindings();
404 else if (this->package_ != NULL)
405 return this->package_->bindings();
407 return this->globals_;
411 Gogo::current_bindings() const
413 if (!this->functions_.empty())
414 return this->functions_.back().blocks.back()->bindings();
415 else if (this->package_ != NULL)
416 return this->package_->bindings();
418 return this->globals_;
421 // Return the current block.
424 Gogo::current_block()
426 if (this->functions_.empty())
429 return this->functions_.back().blocks.back();
432 // Look up a name in the current binding contour. If PFUNCTION is not
433 // NULL, set it to the function in which the name is defined, or NULL
434 // if the name is defined in global scope.
437 Gogo::lookup(const std::string& name, Named_object** pfunction) const
439 if (pfunction != NULL)
442 if (Gogo::is_sink_name(name))
443 return Named_object::make_sink();
445 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
446 p != this->functions_.rend();
449 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
452 if (pfunction != NULL)
453 *pfunction = p->function;
458 if (this->package_ != NULL)
460 Named_object* ret = this->package_->bindings()->lookup(name);
463 if (ret->package() != NULL)
464 ret->package()->set_used();
469 // We do not look in the global namespace. If we did, the global
470 // namespace would effectively hide names which were defined in
471 // package scope which we have not yet seen. Instead,
472 // define_global_names is called after parsing is over to connect
473 // undefined names at package scope with names defined at global
479 // Look up a name in the current block, without searching enclosing
483 Gogo::lookup_in_block(const std::string& name) const
485 go_assert(!this->functions_.empty());
486 go_assert(!this->functions_.back().blocks.empty());
487 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
490 // Look up a name in the global namespace.
493 Gogo::lookup_global(const char* name) const
495 return this->globals_->lookup(name);
498 // Add an imported package.
501 Gogo::add_imported_package(const std::string& real_name,
502 const std::string& alias_arg,
503 bool is_alias_exported,
504 const std::string& unique_prefix,
505 source_location location,
506 bool* padd_to_globals)
508 // FIXME: Now that we compile packages as a whole, should we permit
509 // importing the current package?
510 if (this->package_name() == real_name
511 && this->unique_prefix() == unique_prefix)
513 *padd_to_globals = false;
514 if (!alias_arg.empty() && alias_arg != ".")
516 std::string alias = this->pack_hidden_name(alias_arg,
518 this->package_->bindings()->add_package(alias, this->package_);
520 return this->package_;
522 else if (alias_arg == ".")
524 *padd_to_globals = true;
525 return this->register_package(real_name, unique_prefix, location);
527 else if (alias_arg == "_")
529 Package* ret = this->register_package(real_name, unique_prefix, location);
530 ret->set_uses_sink_alias();
535 *padd_to_globals = false;
536 std::string alias = alias_arg;
540 is_alias_exported = Lex::is_exported_name(alias);
542 alias = this->pack_hidden_name(alias, is_alias_exported);
543 Named_object* no = this->add_package(real_name, alias, unique_prefix,
545 if (!no->is_package())
547 return no->package_value();
554 Gogo::add_package(const std::string& real_name, const std::string& alias,
555 const std::string& unique_prefix, source_location location)
557 go_assert(this->in_global_scope());
559 // Register the package. Note that we might have already seen it in
560 // an earlier import.
561 Package* package = this->register_package(real_name, unique_prefix, location);
563 return this->package_->bindings()->add_package(alias, package);
566 // Register a package. This package may or may not be imported. This
567 // returns the Package structure for the package, creating if it
571 Gogo::register_package(const std::string& package_name,
572 const std::string& unique_prefix,
573 source_location location)
575 go_assert(!unique_prefix.empty() && !package_name.empty());
576 std::string name = unique_prefix + '.' + package_name;
577 Package* package = NULL;
578 std::pair<Packages::iterator, bool> ins =
579 this->packages_.insert(std::make_pair(name, package));
582 // We have seen this package name before.
583 package = ins.first->second;
584 go_assert(package != NULL);
585 go_assert(package->name() == package_name
586 && package->unique_prefix() == unique_prefix);
587 if (package->location() == UNKNOWN_LOCATION)
588 package->set_location(location);
592 // First time we have seen this package name.
593 package = new Package(package_name, unique_prefix, location);
594 go_assert(ins.first->second == NULL);
595 ins.first->second = package;
601 // Start compiling a function.
604 Gogo::start_function(const std::string& name, Function_type* type,
605 bool add_method_to_type, source_location location)
607 bool at_top_level = this->functions_.empty();
609 Block* block = new Block(NULL, location);
611 Function* enclosing = (at_top_level
613 : this->functions_.back().function->func_value());
615 Function* function = new Function(type, enclosing, block, location);
617 if (type->is_method())
619 const Typed_identifier* receiver = type->receiver();
620 Variable* this_param = new Variable(receiver->type(), NULL, false,
621 true, true, location);
622 std::string name = receiver->name();
625 // We need to give receivers a name since they wind up in
626 // DECL_ARGUMENTS. FIXME.
627 static unsigned int count;
629 snprintf(buf, sizeof buf, "r.%u", count);
633 block->bindings()->add_variable(name, NULL, this_param);
636 const Typed_identifier_list* parameters = type->parameters();
637 bool is_varargs = type->is_varargs();
638 if (parameters != NULL)
640 for (Typed_identifier_list::const_iterator p = parameters->begin();
641 p != parameters->end();
644 Variable* param = new Variable(p->type(), NULL, false, true, false,
646 if (is_varargs && p + 1 == parameters->end())
647 param->set_is_varargs_parameter();
649 std::string name = p->name();
650 if (name.empty() || Gogo::is_sink_name(name))
652 // We need to give parameters a name since they wind up
653 // in DECL_ARGUMENTS. FIXME.
654 static unsigned int count;
656 snprintf(buf, sizeof buf, "p.%u", count);
660 block->bindings()->add_variable(name, NULL, param);
664 function->create_result_variables(this);
666 const std::string* pname;
667 std::string nested_name;
668 bool is_init = false;
669 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
671 if ((type->parameters() != NULL && !type->parameters()->empty())
672 || (type->results() != NULL && !type->results()->empty()))
674 "func init must have no arguments and no return values");
675 // There can be multiple "init" functions, so give them each a
677 static int init_count;
679 snprintf(buf, sizeof buf, ".$init%d", init_count);
682 pname = &nested_name;
685 else if (!name.empty())
689 // Invent a name for a nested function.
690 static int nested_count;
692 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
695 pname = &nested_name;
699 if (Gogo::is_sink_name(*pname))
701 static int sink_count;
703 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
705 ret = Named_object::make_function(buf, NULL, function);
707 else if (!type->is_method())
709 ret = this->package_->bindings()->add_function(*pname, NULL, function);
710 if (!ret->is_function() || ret->func_value() != function)
712 // Redefinition error. Invent a name to avoid knockon
714 static int redefinition_count;
716 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
717 ++redefinition_count;
718 ret = this->package_->bindings()->add_function(buf, NULL, function);
723 if (!add_method_to_type)
724 ret = Named_object::make_function(name, NULL, function);
727 go_assert(at_top_level);
728 Type* rtype = type->receiver()->type();
730 // We want to look through the pointer created by the
731 // parser, without getting an error if the type is not yet
733 if (rtype->classification() == Type::TYPE_POINTER)
734 rtype = rtype->points_to();
736 if (rtype->is_error_type())
737 ret = Named_object::make_function(name, NULL, function);
738 else if (rtype->named_type() != NULL)
740 ret = rtype->named_type()->add_method(name, function);
741 if (!ret->is_function())
743 // Redefinition error.
744 ret = Named_object::make_function(name, NULL, function);
747 else if (rtype->forward_declaration_type() != NULL)
749 Named_object* type_no =
750 rtype->forward_declaration_type()->named_object();
751 if (type_no->is_unknown())
753 // If we are seeing methods it really must be a
754 // type. Declare it as such. An alternative would
755 // be to support lists of methods for unknown
756 // expressions. Either way the error messages if
757 // this is not a type are going to get confusing.
758 Named_object* declared =
759 this->declare_package_type(type_no->name(),
760 type_no->location());
762 == type_no->unknown_value()->real_named_object());
764 ret = rtype->forward_declaration_type()->add_method(name,
770 this->package_->bindings()->add_method(ret);
773 this->functions_.resize(this->functions_.size() + 1);
774 Open_function& of(this->functions_.back());
776 of.blocks.push_back(block);
780 this->init_functions_.push_back(ret);
781 this->need_init_fn_ = true;
787 // Finish compiling a function.
790 Gogo::finish_function(source_location location)
792 this->finish_block(location);
793 go_assert(this->functions_.back().blocks.empty());
794 this->functions_.pop_back();
797 // Return the current function.
800 Gogo::current_function() const
802 go_assert(!this->functions_.empty());
803 return this->functions_.back().function;
806 // Start a new block.
809 Gogo::start_block(source_location location)
811 go_assert(!this->functions_.empty());
812 Block* block = new Block(this->current_block(), location);
813 this->functions_.back().blocks.push_back(block);
819 Gogo::finish_block(source_location location)
821 go_assert(!this->functions_.empty());
822 go_assert(!this->functions_.back().blocks.empty());
823 Block* block = this->functions_.back().blocks.back();
824 this->functions_.back().blocks.pop_back();
825 block->set_end_location(location);
829 // Add an unknown name.
832 Gogo::add_unknown_name(const std::string& name, source_location location)
834 return this->package_->bindings()->add_unknown_name(name, location);
837 // Declare a function.
840 Gogo::declare_function(const std::string& name, Function_type* type,
841 source_location location)
843 if (!type->is_method())
844 return this->current_bindings()->add_function_declaration(name, NULL, type,
848 // We don't bother to add this to the list of global
850 Type* rtype = type->receiver()->type();
852 // We want to look through the pointer created by the
853 // parser, without getting an error if the type is not yet
855 if (rtype->classification() == Type::TYPE_POINTER)
856 rtype = rtype->points_to();
858 if (rtype->is_error_type())
860 else if (rtype->named_type() != NULL)
861 return rtype->named_type()->add_method_declaration(name, NULL, type,
863 else if (rtype->forward_declaration_type() != NULL)
865 Forward_declaration_type* ftype = rtype->forward_declaration_type();
866 return ftype->add_method_declaration(name, type, location);
873 // Add a label definition.
876 Gogo::add_label_definition(const std::string& label_name,
877 source_location location)
879 go_assert(!this->functions_.empty());
880 Function* func = this->functions_.back().function->func_value();
881 Label* label = func->add_label_definition(this, label_name, location);
882 this->add_statement(Statement::make_label_statement(label, location));
886 // Add a label reference.
889 Gogo::add_label_reference(const std::string& label_name,
890 source_location location, bool issue_goto_errors)
892 go_assert(!this->functions_.empty());
893 Function* func = this->functions_.back().function->func_value();
894 return func->add_label_reference(this, label_name, location,
898 // Return the current binding state.
901 Gogo::bindings_snapshot(source_location location)
903 return new Bindings_snapshot(this->current_block(), location);
909 Gogo::add_statement(Statement* statement)
911 go_assert(!this->functions_.empty()
912 && !this->functions_.back().blocks.empty());
913 this->functions_.back().blocks.back()->add_statement(statement);
919 Gogo::add_block(Block* block, source_location location)
921 go_assert(!this->functions_.empty()
922 && !this->functions_.back().blocks.empty());
923 Statement* statement = Statement::make_block_statement(block, location);
924 this->functions_.back().blocks.back()->add_statement(statement);
930 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
933 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
939 Gogo::add_type(const std::string& name, Type* type, source_location location)
941 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
943 if (!this->in_global_scope() && no->is_type())
944 no->type_value()->set_in_function(this->functions_.back().function);
950 Gogo::add_named_type(Named_type* type)
952 go_assert(this->in_global_scope());
953 this->current_bindings()->add_named_type(type);
959 Gogo::declare_type(const std::string& name, source_location location)
961 Bindings* bindings = this->current_bindings();
962 Named_object* no = bindings->add_type_declaration(name, NULL, location);
963 if (!this->in_global_scope() && no->is_type_declaration())
965 Named_object* f = this->functions_.back().function;
966 no->type_declaration_value()->set_in_function(f);
971 // Declare a type at the package level.
974 Gogo::declare_package_type(const std::string& name, source_location location)
976 return this->package_->bindings()->add_type_declaration(name, NULL, location);
979 // Define a type which was already declared.
982 Gogo::define_type(Named_object* no, Named_type* type)
984 this->current_bindings()->define_type(no, type);
990 Gogo::add_variable(const std::string& name, Variable* variable)
992 Named_object* no = this->current_bindings()->add_variable(name, NULL,
995 // In a function the middle-end wants to see a DECL_EXPR node.
998 && !no->var_value()->is_parameter()
999 && !this->functions_.empty())
1000 this->add_statement(Statement::make_variable_declaration(no));
1005 // Add a sink--a reference to the blank identifier _.
1010 return Named_object::make_sink();
1013 // Add a named object.
1016 Gogo::add_named_object(Named_object* no)
1018 this->current_bindings()->add_named_object(no);
1021 // Record that we've seen an interface type.
1024 Gogo::record_interface_type(Interface_type* itype)
1026 this->interface_types_.push_back(itype);
1029 // Return a name for a thunk object.
1034 static int thunk_count;
1035 char thunk_name[50];
1036 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1041 // Return whether a function is a thunk.
1044 Gogo::is_thunk(const Named_object* no)
1046 return no->name().compare(0, 6, "$thunk") == 0;
1049 // Define the global names. We do this only after parsing all the
1050 // input files, because the program might define the global names
1054 Gogo::define_global_names()
1056 for (Bindings::const_declarations_iterator p =
1057 this->globals_->begin_declarations();
1058 p != this->globals_->end_declarations();
1061 Named_object* global_no = p->second;
1062 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1063 Named_object* no = this->package_->bindings()->lookup(name);
1067 if (no->is_type_declaration())
1069 if (global_no->is_type())
1071 if (no->type_declaration_value()->has_methods())
1072 error_at(no->location(),
1073 "may not define methods for global type");
1074 no->set_type_value(global_no->type_value());
1078 error_at(no->location(), "expected type");
1079 Type* errtype = Type::make_error_type();
1080 Named_object* err = Named_object::make_type("error", NULL,
1083 no->set_type_value(err->type_value());
1086 else if (no->is_unknown())
1087 no->unknown_value()->set_real_named_object(global_no);
1091 // Clear out names in file scope.
1094 Gogo::clear_file_scope()
1096 this->package_->bindings()->clear_file_scope();
1098 // Warn about packages which were imported but not used.
1099 for (Packages::iterator p = this->packages_.begin();
1100 p != this->packages_.end();
1103 Package* package = p->second;
1104 if (package != this->package_
1105 && package->is_imported()
1107 && !package->uses_sink_alias()
1109 error_at(package->location(), "imported and not used: %s",
1110 Gogo::message_name(package->name()).c_str());
1111 package->clear_is_imported();
1112 package->clear_uses_sink_alias();
1113 package->clear_used();
1117 // Traverse the tree.
1120 Gogo::traverse(Traverse* traverse)
1122 // Traverse the current package first for consistency. The other
1123 // packages will only contain imported types, constants, and
1125 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1127 for (Packages::const_iterator p = this->packages_.begin();
1128 p != this->packages_.end();
1131 if (p->second != this->package_)
1133 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1139 // Traversal class used to verify types.
1141 class Verify_types : public Traverse
1145 : Traverse(traverse_types)
1152 // Verify that a type is correct.
1155 Verify_types::type(Type* t)
1158 return TRAVERSE_SKIP_COMPONENTS;
1159 return TRAVERSE_CONTINUE;
1162 // Verify that all types are correct.
1165 Gogo::verify_types()
1167 Verify_types traverse;
1168 this->traverse(&traverse);
1171 // Traversal class used to lower parse tree.
1173 class Lower_parse_tree : public Traverse
1176 Lower_parse_tree(Gogo* gogo, Named_object* function)
1177 : Traverse(traverse_variables
1178 | traverse_constants
1179 | traverse_functions
1180 | traverse_statements
1181 | traverse_expressions),
1182 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1186 set_inserter(const Statement_inserter* inserter)
1187 { this->inserter_ = *inserter; }
1190 variable(Named_object*);
1193 constant(Named_object*, bool);
1196 function(Named_object*);
1199 statement(Block*, size_t* pindex, Statement*);
1202 expression(Expression**);
1207 // The function we are traversing.
1208 Named_object* function_;
1209 // Value to use for the predeclared constant iota.
1211 // Current statement inserter for use by expressions.
1212 Statement_inserter inserter_;
1218 Lower_parse_tree::variable(Named_object* no)
1220 if (!no->is_variable())
1221 return TRAVERSE_CONTINUE;
1223 if (no->is_variable() && no->var_value()->is_global())
1225 // Global variables can have loops in their initialization
1226 // expressions. This is handled in lower_init_expression.
1227 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1229 return TRAVERSE_CONTINUE;
1232 // This is a local variable. We are going to return
1233 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1234 // initialization expression when we reach the variable declaration
1235 // statement. However, that means that we need to traverse the type
1237 if (no->var_value()->has_type())
1239 Type* type = no->var_value()->type();
1242 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1243 return TRAVERSE_EXIT;
1246 go_assert(!no->var_value()->has_pre_init());
1248 return TRAVERSE_SKIP_COMPONENTS;
1251 // Lower constants. We handle constants specially so that we can set
1252 // the right value for the predeclared constant iota. This works in
1253 // conjunction with the way we lower Const_expression objects.
1256 Lower_parse_tree::constant(Named_object* no, bool)
1258 Named_constant* nc = no->const_value();
1260 // Don't get into trouble if the constant's initializer expression
1261 // refers to the constant itself.
1263 return TRAVERSE_CONTINUE;
1266 go_assert(this->iota_value_ == -1);
1267 this->iota_value_ = nc->iota_value();
1268 nc->traverse_expression(this);
1269 this->iota_value_ = -1;
1271 nc->clear_lowering();
1273 // We will traverse the expression a second time, but that will be
1276 return TRAVERSE_CONTINUE;
1279 // Lower function closure types. Record the function while lowering
1280 // it, so that we can pass it down when lowering an expression.
1283 Lower_parse_tree::function(Named_object* no)
1285 no->func_value()->set_closure_type();
1287 go_assert(this->function_ == NULL);
1288 this->function_ = no;
1289 int t = no->func_value()->traverse(this);
1290 this->function_ = NULL;
1292 if (t == TRAVERSE_EXIT)
1294 return TRAVERSE_SKIP_COMPONENTS;
1297 // Lower statement parse trees.
1300 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1302 // Because we explicitly traverse the statement's contents
1303 // ourselves, we want to skip block statements here. There is
1304 // nothing to lower in a block statement.
1305 if (sorig->is_block_statement())
1306 return TRAVERSE_CONTINUE;
1308 Statement_inserter hold_inserter(this->inserter_);
1309 this->inserter_ = Statement_inserter(block, pindex);
1311 // Lower the expressions first.
1312 int t = sorig->traverse_contents(this);
1313 if (t == TRAVERSE_EXIT)
1315 this->inserter_ = hold_inserter;
1319 // Keep lowering until nothing changes.
1320 Statement* s = sorig;
1323 Statement* snew = s->lower(this->gogo_, this->function_, block,
1328 t = s->traverse_contents(this);
1329 if (t == TRAVERSE_EXIT)
1331 this->inserter_ = hold_inserter;
1337 block->replace_statement(*pindex, s);
1339 this->inserter_ = hold_inserter;
1340 return TRAVERSE_SKIP_COMPONENTS;
1343 // Lower expression parse trees.
1346 Lower_parse_tree::expression(Expression** pexpr)
1348 // We have to lower all subexpressions first, so that we can get
1349 // their type if necessary. This is awkward, because we don't have
1350 // a postorder traversal pass.
1351 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1352 return TRAVERSE_EXIT;
1353 // Keep lowering until nothing changes.
1356 Expression* e = *pexpr;
1357 Expression* enew = e->lower(this->gogo_, this->function_,
1358 &this->inserter_, this->iota_value_);
1363 return TRAVERSE_SKIP_COMPONENTS;
1366 // Lower the parse tree. This is called after the parse is complete,
1367 // when all names should be resolved.
1370 Gogo::lower_parse_tree()
1372 Lower_parse_tree lower_parse_tree(this, NULL);
1373 this->traverse(&lower_parse_tree);
1379 Gogo::lower_block(Named_object* function, Block* block)
1381 Lower_parse_tree lower_parse_tree(this, function);
1382 block->traverse(&lower_parse_tree);
1385 // Lower an expression. INSERTER may be NULL, in which case the
1386 // expression had better not need to create any temporaries.
1389 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1392 Lower_parse_tree lower_parse_tree(this, function);
1393 if (inserter != NULL)
1394 lower_parse_tree.set_inserter(inserter);
1395 lower_parse_tree.expression(pexpr);
1398 // Lower a constant. This is called when lowering a reference to a
1399 // constant. We have to make sure that the constant has already been
1403 Gogo::lower_constant(Named_object* no)
1405 go_assert(no->is_const());
1406 Lower_parse_tree lower(this, NULL);
1407 lower.constant(no, false);
1410 // Look for interface types to finalize methods of inherited
1413 class Finalize_methods : public Traverse
1416 Finalize_methods(Gogo* gogo)
1417 : Traverse(traverse_types),
1428 // Finalize the methods of an interface type.
1431 Finalize_methods::type(Type* t)
1433 // Check the classification so that we don't finalize the methods
1434 // twice for a named interface type.
1435 switch (t->classification())
1437 case Type::TYPE_INTERFACE:
1438 t->interface_type()->finalize_methods();
1441 case Type::TYPE_NAMED:
1443 // We have to finalize the methods of the real type first.
1444 // But if the real type is a struct type, then we only want to
1445 // finalize the methods of the field types, not of the struct
1446 // type itself. We don't want to add methods to the struct,
1447 // since it has a name.
1448 Type* rt = t->named_type()->real_type();
1449 if (rt->classification() != Type::TYPE_STRUCT)
1451 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1452 return TRAVERSE_EXIT;
1456 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1457 return TRAVERSE_EXIT;
1460 t->named_type()->finalize_methods(this->gogo_);
1462 return TRAVERSE_SKIP_COMPONENTS;
1465 case Type::TYPE_STRUCT:
1466 t->struct_type()->finalize_methods(this->gogo_);
1473 return TRAVERSE_CONTINUE;
1476 // Finalize method lists and build stub methods for types.
1479 Gogo::finalize_methods()
1481 Finalize_methods finalize(this);
1482 this->traverse(&finalize);
1485 // Set types for unspecified variables and constants.
1488 Gogo::determine_types()
1490 Bindings* bindings = this->current_bindings();
1491 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1492 p != bindings->end_definitions();
1495 if ((*p)->is_function())
1496 (*p)->func_value()->determine_types();
1497 else if ((*p)->is_variable())
1498 (*p)->var_value()->determine_type();
1499 else if ((*p)->is_const())
1500 (*p)->const_value()->determine_type();
1502 // See if a variable requires us to build an initialization
1503 // function. We know that we will see all global variables
1505 if (!this->need_init_fn_ && (*p)->is_variable())
1507 Variable* variable = (*p)->var_value();
1509 // If this is a global variable which requires runtime
1510 // initialization, we need an initialization function.
1511 if (!variable->is_global())
1513 else if (variable->init() == NULL)
1515 else if (variable->type()->interface_type() != NULL)
1516 this->need_init_fn_ = true;
1517 else if (variable->init()->is_constant())
1519 else if (!variable->init()->is_composite_literal())
1520 this->need_init_fn_ = true;
1521 else if (variable->init()->is_nonconstant_composite_literal())
1522 this->need_init_fn_ = true;
1524 // If this is a global variable which holds a pointer value,
1525 // then we need an initialization function to register it as a
1527 if (variable->is_global() && variable->type()->has_pointer())
1528 this->need_init_fn_ = true;
1532 // Determine the types of constants in packages.
1533 for (Packages::const_iterator p = this->packages_.begin();
1534 p != this->packages_.end();
1536 p->second->determine_types();
1539 // Traversal class used for type checking.
1541 class Check_types_traverse : public Traverse
1544 Check_types_traverse(Gogo* gogo)
1545 : Traverse(traverse_variables
1546 | traverse_constants
1547 | traverse_functions
1548 | traverse_statements
1549 | traverse_expressions),
1554 variable(Named_object*);
1557 constant(Named_object*, bool);
1560 function(Named_object*);
1563 statement(Block*, size_t* pindex, Statement*);
1566 expression(Expression**);
1573 // Check that a variable initializer has the right type.
1576 Check_types_traverse::variable(Named_object* named_object)
1578 if (named_object->is_variable())
1580 Variable* var = named_object->var_value();
1582 // Give error if variable type is not defined.
1583 var->type()->base();
1585 Expression* init = var->init();
1588 && !Type::are_assignable(var->type(), init->type(), &reason))
1591 error_at(var->location(), "incompatible type in initialization");
1593 error_at(var->location(),
1594 "incompatible type in initialization (%s)",
1599 return TRAVERSE_CONTINUE;
1602 // Check that a constant initializer has the right type.
1605 Check_types_traverse::constant(Named_object* named_object, bool)
1607 Named_constant* constant = named_object->const_value();
1608 Type* ctype = constant->type();
1609 if (ctype->integer_type() == NULL
1610 && ctype->float_type() == NULL
1611 && ctype->complex_type() == NULL
1612 && !ctype->is_boolean_type()
1613 && !ctype->is_string_type())
1615 if (ctype->is_nil_type())
1616 error_at(constant->location(), "const initializer cannot be nil");
1617 else if (!ctype->is_error())
1618 error_at(constant->location(), "invalid constant type");
1619 constant->set_error();
1621 else if (!constant->expr()->is_constant())
1623 error_at(constant->expr()->location(), "expression is not constant");
1624 constant->set_error();
1626 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1629 error_at(constant->location(),
1630 "initialization expression has wrong type");
1631 constant->set_error();
1633 return TRAVERSE_CONTINUE;
1636 // There are no types to check in a function, but this is where we
1637 // issue warnings about labels which are defined but not referenced.
1640 Check_types_traverse::function(Named_object* no)
1642 no->func_value()->check_labels();
1643 return TRAVERSE_CONTINUE;
1646 // Check that types are valid in a statement.
1649 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1651 s->check_types(this->gogo_);
1652 return TRAVERSE_CONTINUE;
1655 // Check that types are valid in an expression.
1658 Check_types_traverse::expression(Expression** expr)
1660 (*expr)->check_types(this->gogo_);
1661 return TRAVERSE_CONTINUE;
1664 // Check that types are valid.
1669 Check_types_traverse traverse(this);
1670 this->traverse(&traverse);
1673 // Check the types in a single block.
1676 Gogo::check_types_in_block(Block* block)
1678 Check_types_traverse traverse(this);
1679 block->traverse(&traverse);
1682 // A traversal class used to find a single shortcut operator within an
1685 class Find_shortcut : public Traverse
1689 : Traverse(traverse_blocks
1690 | traverse_statements
1691 | traverse_expressions),
1695 // A pointer to the expression which was found, or NULL if none was
1699 { return this->found_; }
1704 { return TRAVERSE_SKIP_COMPONENTS; }
1707 statement(Block*, size_t*, Statement*)
1708 { return TRAVERSE_SKIP_COMPONENTS; }
1711 expression(Expression**);
1714 Expression** found_;
1717 // Find a shortcut expression.
1720 Find_shortcut::expression(Expression** pexpr)
1722 Expression* expr = *pexpr;
1723 Binary_expression* be = expr->binary_expression();
1725 return TRAVERSE_CONTINUE;
1726 Operator op = be->op();
1727 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1728 return TRAVERSE_CONTINUE;
1729 go_assert(this->found_ == NULL);
1730 this->found_ = pexpr;
1731 return TRAVERSE_EXIT;
1734 // A traversal class used to turn shortcut operators into explicit if
1737 class Shortcuts : public Traverse
1740 Shortcuts(Gogo* gogo)
1741 : Traverse(traverse_variables
1742 | traverse_statements),
1748 variable(Named_object*);
1751 statement(Block*, size_t*, Statement*);
1754 // Convert a shortcut operator.
1756 convert_shortcut(Block* enclosing, Expression** pshortcut);
1762 // Remove shortcut operators in a single statement.
1765 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1767 // FIXME: This approach doesn't work for switch statements, because
1768 // we add the new statements before the whole switch when we need to
1769 // instead add them just before the switch expression. The right
1770 // fix is probably to lower switch statements with nonconstant cases
1771 // to a series of conditionals.
1772 if (s->switch_statement() != NULL)
1773 return TRAVERSE_CONTINUE;
1777 Find_shortcut find_shortcut;
1779 // If S is a variable declaration, then ordinary traversal won't
1780 // do anything. We want to explicitly traverse the
1781 // initialization expression if there is one.
1782 Variable_declaration_statement* vds = s->variable_declaration_statement();
1783 Expression* init = NULL;
1785 s->traverse_contents(&find_shortcut);
1788 init = vds->var()->var_value()->init();
1790 return TRAVERSE_CONTINUE;
1791 init->traverse(&init, &find_shortcut);
1793 Expression** pshortcut = find_shortcut.found();
1794 if (pshortcut == NULL)
1795 return TRAVERSE_CONTINUE;
1797 Statement* snew = this->convert_shortcut(block, pshortcut);
1798 block->insert_statement_before(*pindex, snew);
1801 if (pshortcut == &init)
1802 vds->var()->var_value()->set_init(init);
1806 // Remove shortcut operators in the initializer of a global variable.
1809 Shortcuts::variable(Named_object* no)
1811 if (no->is_result_variable())
1812 return TRAVERSE_CONTINUE;
1813 Variable* var = no->var_value();
1814 Expression* init = var->init();
1815 if (!var->is_global() || init == NULL)
1816 return TRAVERSE_CONTINUE;
1820 Find_shortcut find_shortcut;
1821 init->traverse(&init, &find_shortcut);
1822 Expression** pshortcut = find_shortcut.found();
1823 if (pshortcut == NULL)
1824 return TRAVERSE_CONTINUE;
1826 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1827 var->add_preinit_statement(this->gogo_, snew);
1828 if (pshortcut == &init)
1829 var->set_init(init);
1833 // Given an expression which uses a shortcut operator, return a
1834 // statement which implements it, and update *PSHORTCUT accordingly.
1837 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1839 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1840 Expression* left = shortcut->left();
1841 Expression* right = shortcut->right();
1842 source_location loc = shortcut->location();
1844 Block* retblock = new Block(enclosing, loc);
1845 retblock->set_end_location(loc);
1847 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
1849 retblock->add_statement(ts);
1851 Block* block = new Block(retblock, loc);
1852 block->set_end_location(loc);
1853 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1854 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1855 block->add_statement(assign);
1857 Expression* cond = Expression::make_temporary_reference(ts, loc);
1858 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1859 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1861 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1863 retblock->add_statement(if_statement);
1865 *pshortcut = Expression::make_temporary_reference(ts, loc);
1869 // Now convert any shortcut operators in LEFT and RIGHT.
1870 Shortcuts shortcuts(this->gogo_);
1871 retblock->traverse(&shortcuts);
1873 return Statement::make_block_statement(retblock, loc);
1876 // Turn shortcut operators into explicit if statements. Doing this
1877 // considerably simplifies the order of evaluation rules.
1880 Gogo::remove_shortcuts()
1882 Shortcuts shortcuts(this);
1883 this->traverse(&shortcuts);
1886 // A traversal class which finds all the expressions which must be
1887 // evaluated in order within a statement or larger expression. This
1888 // is used to implement the rules about order of evaluation.
1890 class Find_eval_ordering : public Traverse
1893 typedef std::vector<Expression**> Expression_pointers;
1896 Find_eval_ordering()
1897 : Traverse(traverse_blocks
1898 | traverse_statements
1899 | traverse_expressions),
1905 { return this->exprs_.size(); }
1907 typedef Expression_pointers::const_iterator const_iterator;
1911 { return this->exprs_.begin(); }
1915 { return this->exprs_.end(); }
1920 { return TRAVERSE_SKIP_COMPONENTS; }
1923 statement(Block*, size_t*, Statement*)
1924 { return TRAVERSE_SKIP_COMPONENTS; }
1927 expression(Expression**);
1930 // A list of pointers to expressions with side-effects.
1931 Expression_pointers exprs_;
1934 // If an expression must be evaluated in order, put it on the list.
1937 Find_eval_ordering::expression(Expression** expression_pointer)
1939 // We have to look at subexpressions before this one.
1940 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1941 return TRAVERSE_EXIT;
1942 if ((*expression_pointer)->must_eval_in_order())
1943 this->exprs_.push_back(expression_pointer);
1944 return TRAVERSE_SKIP_COMPONENTS;
1947 // A traversal class for ordering evaluations.
1949 class Order_eval : public Traverse
1952 Order_eval(Gogo* gogo)
1953 : Traverse(traverse_variables
1954 | traverse_statements),
1959 variable(Named_object*);
1962 statement(Block*, size_t*, Statement*);
1969 // Implement the order of evaluation rules for a statement.
1972 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1974 // FIXME: This approach doesn't work for switch statements, because
1975 // we add the new statements before the whole switch when we need to
1976 // instead add them just before the switch expression. The right
1977 // fix is probably to lower switch statements with nonconstant cases
1978 // to a series of conditionals.
1979 if (s->switch_statement() != NULL)
1980 return TRAVERSE_CONTINUE;
1982 Find_eval_ordering find_eval_ordering;
1984 // If S is a variable declaration, then ordinary traversal won't do
1985 // anything. We want to explicitly traverse the initialization
1986 // expression if there is one.
1987 Variable_declaration_statement* vds = s->variable_declaration_statement();
1988 Expression* init = NULL;
1989 Expression* orig_init = NULL;
1991 s->traverse_contents(&find_eval_ordering);
1994 init = vds->var()->var_value()->init();
1996 return TRAVERSE_CONTINUE;
1999 // It might seem that this could be
2000 // init->traverse_subexpressions. Unfortunately that can fail
2003 // newvar, err := call(arg())
2004 // Here newvar will have an init of call result 0 of
2005 // call(arg()). If we only traverse subexpressions, we will
2006 // only find arg(), and we won't bother to move anything out.
2007 // Then we get to the assignment to err, we will traverse the
2008 // whole statement, and this time we will find both call() and
2009 // arg(), and so we will move them out. This will cause them to
2010 // be put into temporary variables before the assignment to err
2011 // but after the declaration of newvar. To avoid that problem,
2012 // we traverse the entire expression here.
2013 Expression::traverse(&init, &find_eval_ordering);
2016 if (find_eval_ordering.size() <= 1)
2018 // If there is only one expression with a side-effect, we can
2019 // leave it in place.
2020 return TRAVERSE_CONTINUE;
2023 bool is_thunk = s->thunk_statement() != NULL;
2024 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2025 p != find_eval_ordering.end();
2028 Expression** pexpr = *p;
2030 // The last expression in a thunk will be the call passed to go
2031 // or defer, which we must not evaluate early.
2032 if (is_thunk && p + 1 == find_eval_ordering.end())
2035 source_location loc = (*pexpr)->location();
2037 if ((*pexpr)->call_expression() == NULL
2038 || (*pexpr)->call_expression()->result_count() < 2)
2040 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2043 *pexpr = Expression::make_temporary_reference(ts, loc);
2047 // A call expression which returns multiple results needs to
2048 // be handled specially. We can't create a temporary
2049 // because there is no type to give it. Any actual uses of
2050 // the values will be done via Call_result_expressions.
2051 s = Statement::make_statement(*pexpr, true);
2054 block->insert_statement_before(*pindex, s);
2058 if (init != orig_init)
2059 vds->var()->var_value()->set_init(init);
2061 return TRAVERSE_CONTINUE;
2064 // Implement the order of evaluation rules for the initializer of a
2068 Order_eval::variable(Named_object* no)
2070 if (no->is_result_variable())
2071 return TRAVERSE_CONTINUE;
2072 Variable* var = no->var_value();
2073 Expression* init = var->init();
2074 if (!var->is_global() || init == NULL)
2075 return TRAVERSE_CONTINUE;
2077 Find_eval_ordering find_eval_ordering;
2078 Expression::traverse(&init, &find_eval_ordering);
2080 if (find_eval_ordering.size() <= 1)
2082 // If there is only one expression with a side-effect, we can
2083 // leave it in place.
2084 return TRAVERSE_SKIP_COMPONENTS;
2087 Expression* orig_init = init;
2089 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2090 p != find_eval_ordering.end();
2093 Expression** pexpr = *p;
2094 source_location loc = (*pexpr)->location();
2096 if ((*pexpr)->call_expression() == NULL
2097 || (*pexpr)->call_expression()->result_count() < 2)
2099 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2102 *pexpr = Expression::make_temporary_reference(ts, loc);
2106 // A call expression which returns multiple results needs to
2107 // be handled specially.
2108 s = Statement::make_statement(*pexpr, true);
2110 var->add_preinit_statement(this->gogo_, s);
2113 if (init != orig_init)
2114 var->set_init(init);
2116 return TRAVERSE_SKIP_COMPONENTS;
2119 // Use temporary variables to implement the order of evaluation rules.
2122 Gogo::order_evaluations()
2124 Order_eval order_eval(this);
2125 this->traverse(&order_eval);
2128 // Traversal to convert calls to the predeclared recover function to
2129 // pass in an argument indicating whether it can recover from a panic
2132 class Convert_recover : public Traverse
2135 Convert_recover(Named_object* arg)
2136 : Traverse(traverse_expressions),
2142 expression(Expression**);
2145 // The argument to pass to the function.
2149 // Convert calls to recover.
2152 Convert_recover::expression(Expression** pp)
2154 Call_expression* ce = (*pp)->call_expression();
2155 if (ce != NULL && ce->is_recover_call())
2156 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2158 return TRAVERSE_CONTINUE;
2161 // Traversal for build_recover_thunks.
2163 class Build_recover_thunks : public Traverse
2166 Build_recover_thunks(Gogo* gogo)
2167 : Traverse(traverse_functions),
2172 function(Named_object*);
2176 can_recover_arg(source_location);
2182 // If this function calls recover, turn it into a thunk.
2185 Build_recover_thunks::function(Named_object* orig_no)
2187 Function* orig_func = orig_no->func_value();
2188 if (!orig_func->calls_recover()
2189 || orig_func->is_recover_thunk()
2190 || orig_func->has_recover_thunk())
2191 return TRAVERSE_CONTINUE;
2193 Gogo* gogo = this->gogo_;
2194 source_location location = orig_func->location();
2199 Function_type* orig_fntype = orig_func->type();
2200 Typed_identifier_list* new_params = new Typed_identifier_list();
2201 std::string receiver_name;
2202 if (orig_fntype->is_method())
2204 const Typed_identifier* receiver = orig_fntype->receiver();
2205 snprintf(buf, sizeof buf, "rt.%u", count);
2207 receiver_name = buf;
2208 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2209 receiver->location()));
2211 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2212 if (orig_params != NULL && !orig_params->empty())
2214 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2215 p != orig_params->end();
2218 snprintf(buf, sizeof buf, "pt.%u", count);
2220 new_params->push_back(Typed_identifier(buf, p->type(),
2224 snprintf(buf, sizeof buf, "pr.%u", count);
2226 std::string can_recover_name = buf;
2227 new_params->push_back(Typed_identifier(can_recover_name,
2228 Type::lookup_bool_type(),
2229 orig_fntype->location()));
2231 const Typed_identifier_list* orig_results = orig_fntype->results();
2232 Typed_identifier_list* new_results;
2233 if (orig_results == NULL || orig_results->empty())
2237 new_results = new Typed_identifier_list();
2238 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2239 p != orig_results->end();
2241 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2244 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2246 orig_fntype->location());
2247 if (orig_fntype->is_varargs())
2248 new_fntype->set_is_varargs();
2250 std::string name = orig_no->name() + "$recover";
2251 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2253 Function *new_func = new_no->func_value();
2254 if (orig_func->enclosing() != NULL)
2255 new_func->set_enclosing(orig_func->enclosing());
2257 // We build the code for the original function attached to the new
2258 // function, and then swap the original and new function bodies.
2259 // This means that existing references to the original function will
2260 // then refer to the new function. That makes this code a little
2261 // confusing, in that the reference to NEW_NO really refers to the
2262 // other function, not the one we are building.
2264 Expression* closure = NULL;
2265 if (orig_func->needs_closure())
2267 Named_object* orig_closure_no = orig_func->closure_var();
2268 Variable* orig_closure_var = orig_closure_no->var_value();
2269 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2270 true, false, location);
2271 snprintf(buf, sizeof buf, "closure.%u", count);
2273 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2275 new_func->set_closure_var(new_closure_no);
2276 closure = Expression::make_var_reference(new_closure_no, location);
2279 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2281 Expression_list* args = new Expression_list();
2282 if (new_params != NULL)
2284 // Note that we skip the last parameter, which is the boolean
2285 // indicating whether recover can succed.
2286 for (Typed_identifier_list::const_iterator p = new_params->begin();
2287 p + 1 != new_params->end();
2290 Named_object* p_no = gogo->lookup(p->name(), NULL);
2291 go_assert(p_no != NULL
2292 && p_no->is_variable()
2293 && p_no->var_value()->is_parameter());
2294 args->push_back(Expression::make_var_reference(p_no, location));
2297 args->push_back(this->can_recover_arg(location));
2299 gogo->start_block(location);
2301 Call_expression* call = Expression::make_call(fn, args, false, location);
2304 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2305 s = Statement::make_statement(call, true);
2308 Expression_list* vals = new Expression_list();
2309 size_t rc = orig_fntype->results()->size();
2311 vals->push_back(call);
2314 for (size_t i = 0; i < rc; ++i)
2315 vals->push_back(Expression::make_call_result(call, i));
2317 s = Statement::make_return_statement(vals, location);
2319 s->determine_types();
2320 gogo->add_statement(s);
2322 Block* b = gogo->finish_block(location);
2324 gogo->add_block(b, location);
2326 // Lower the call in case it returns multiple results.
2327 gogo->lower_block(new_no, b);
2329 gogo->finish_function(location);
2331 // Swap the function bodies and types.
2332 new_func->swap_for_recover(orig_func);
2333 orig_func->set_is_recover_thunk();
2334 new_func->set_calls_recover();
2335 new_func->set_has_recover_thunk();
2337 Bindings* orig_bindings = orig_func->block()->bindings();
2338 Bindings* new_bindings = new_func->block()->bindings();
2339 if (orig_fntype->is_method())
2341 // We changed the receiver to be a regular parameter. We have
2342 // to update the binding accordingly in both functions.
2343 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2344 go_assert(orig_rec_no != NULL
2345 && orig_rec_no->is_variable()
2346 && !orig_rec_no->var_value()->is_receiver());
2347 orig_rec_no->var_value()->set_is_receiver();
2349 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2350 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2351 if (new_rec_no == NULL)
2352 go_assert(saw_errors());
2355 go_assert(new_rec_no->is_variable()
2356 && new_rec_no->var_value()->is_receiver());
2357 new_rec_no->var_value()->set_is_not_receiver();
2361 // Because we flipped blocks but not types, the can_recover
2362 // parameter appears in the (now) old bindings as a parameter.
2363 // Change it to a local variable, whereupon it will be discarded.
2364 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2365 go_assert(can_recover_no != NULL
2366 && can_recover_no->is_variable()
2367 && can_recover_no->var_value()->is_parameter());
2368 orig_bindings->remove_binding(can_recover_no);
2370 // Add the can_recover argument to the (now) new bindings, and
2371 // attach it to any recover statements.
2372 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2373 false, true, false, location);
2374 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2376 Convert_recover convert_recover(can_recover_no);
2377 new_func->traverse(&convert_recover);
2379 // Update the function pointers in any named results.
2380 new_func->update_result_variables();
2381 orig_func->update_result_variables();
2383 return TRAVERSE_CONTINUE;
2386 // Return the expression to pass for the .can_recover parameter to the
2387 // new function. This indicates whether a call to recover may return
2388 // non-nil. The expression is
2389 // __go_can_recover(__builtin_return_address()).
2392 Build_recover_thunks::can_recover_arg(source_location location)
2394 static Named_object* builtin_return_address;
2395 if (builtin_return_address == NULL)
2397 const source_location bloc = BUILTINS_LOCATION;
2399 Typed_identifier_list* param_types = new Typed_identifier_list();
2400 Type* uint_type = Type::lookup_integer_type("uint");
2401 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2403 Typed_identifier_list* return_types = new Typed_identifier_list();
2404 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2405 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2407 Function_type* fntype = Type::make_function_type(NULL, param_types,
2408 return_types, bloc);
2409 builtin_return_address =
2410 Named_object::make_function_declaration("__builtin_return_address",
2411 NULL, fntype, bloc);
2412 const char* n = "__builtin_return_address";
2413 builtin_return_address->func_declaration_value()->set_asm_name(n);
2416 static Named_object* can_recover;
2417 if (can_recover == NULL)
2419 const source_location bloc = BUILTINS_LOCATION;
2420 Typed_identifier_list* param_types = new Typed_identifier_list();
2421 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2422 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2423 Type* boolean_type = Type::lookup_bool_type();
2424 Typed_identifier_list* results = new Typed_identifier_list();
2425 results->push_back(Typed_identifier("", boolean_type, bloc));
2426 Function_type* fntype = Type::make_function_type(NULL, param_types,
2428 can_recover = Named_object::make_function_declaration("__go_can_recover",
2431 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2434 Expression* fn = Expression::make_func_reference(builtin_return_address,
2438 mpz_init_set_ui(zval, 0UL);
2439 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2441 Expression_list *args = new Expression_list();
2442 args->push_back(zexpr);
2444 Expression* call = Expression::make_call(fn, args, false, location);
2446 args = new Expression_list();
2447 args->push_back(call);
2449 fn = Expression::make_func_reference(can_recover, NULL, location);
2450 return Expression::make_call(fn, args, false, location);
2453 // Build thunks for functions which call recover. We build a new
2454 // function with an extra parameter, which is whether a call to
2455 // recover can succeed. We then move the body of this function to
2456 // that one. We then turn this function into a thunk which calls the
2457 // new one, passing the value of
2458 // __go_can_recover(__builtin_return_address()). The function will be
2459 // marked as not splitting the stack. This will cooperate with the
2460 // implementation of defer to make recover do the right thing.
2463 Gogo::build_recover_thunks()
2465 Build_recover_thunks build_recover_thunks(this);
2466 this->traverse(&build_recover_thunks);
2469 // Look for named types to see whether we need to create an interface
2472 class Build_method_tables : public Traverse
2475 Build_method_tables(Gogo* gogo,
2476 const std::vector<Interface_type*>& interfaces)
2477 : Traverse(traverse_types),
2478 gogo_(gogo), interfaces_(interfaces)
2487 // A list of locally defined interfaces which have hidden methods.
2488 const std::vector<Interface_type*>& interfaces_;
2491 // Build all required interface method tables for types. We need to
2492 // ensure that we have an interface method table for every interface
2493 // which has a hidden method, for every named type which implements
2494 // that interface. Normally we can just build interface method tables
2495 // as we need them. However, in some cases we can require an
2496 // interface method table for an interface defined in a different
2497 // package for a type defined in that package. If that interface and
2498 // type both use a hidden method, that is OK. However, we will not be
2499 // able to build that interface method table when we need it, because
2500 // the type's hidden method will be static. So we have to build it
2501 // here, and just refer it from other packages as needed.
2504 Gogo::build_interface_method_tables()
2506 std::vector<Interface_type*> hidden_interfaces;
2507 hidden_interfaces.reserve(this->interface_types_.size());
2508 for (std::vector<Interface_type*>::const_iterator pi =
2509 this->interface_types_.begin();
2510 pi != this->interface_types_.end();
2513 const Typed_identifier_list* methods = (*pi)->methods();
2514 if (methods == NULL)
2516 for (Typed_identifier_list::const_iterator pm = methods->begin();
2517 pm != methods->end();
2520 if (Gogo::is_hidden_name(pm->name()))
2522 hidden_interfaces.push_back(*pi);
2528 if (!hidden_interfaces.empty())
2530 // Now traverse the tree looking for all named types.
2531 Build_method_tables bmt(this, hidden_interfaces);
2532 this->traverse(&bmt);
2535 // We no longer need the list of interfaces.
2537 this->interface_types_.clear();
2540 // This is called for each type. For a named type, for each of the
2541 // interfaces with hidden methods that it implements, create the
2545 Build_method_tables::type(Type* type)
2547 Named_type* nt = type->named_type();
2550 for (std::vector<Interface_type*>::const_iterator p =
2551 this->interfaces_.begin();
2552 p != this->interfaces_.end();
2555 // We ask whether a pointer to the named type implements the
2556 // interface, because a pointer can implement more methods
2558 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2560 nt->interface_method_table(this->gogo_, *p, false);
2561 nt->interface_method_table(this->gogo_, *p, true);
2565 return TRAVERSE_CONTINUE;
2568 // Traversal class used to check for return statements.
2570 class Check_return_statements_traverse : public Traverse
2573 Check_return_statements_traverse()
2574 : Traverse(traverse_functions)
2578 function(Named_object*);
2581 // Check that a function has a return statement if it needs one.
2584 Check_return_statements_traverse::function(Named_object* no)
2586 Function* func = no->func_value();
2587 const Function_type* fntype = func->type();
2588 const Typed_identifier_list* results = fntype->results();
2590 // We only need a return statement if there is a return value.
2591 if (results == NULL || results->empty())
2592 return TRAVERSE_CONTINUE;
2594 if (func->block()->may_fall_through())
2595 error_at(func->location(), "control reaches end of non-void function");
2597 return TRAVERSE_CONTINUE;
2600 // Check return statements.
2603 Gogo::check_return_statements()
2605 Check_return_statements_traverse traverse;
2606 this->traverse(&traverse);
2609 // Get the unique prefix to use before all exported symbols. This
2610 // must be unique across the entire link.
2613 Gogo::unique_prefix() const
2615 go_assert(!this->unique_prefix_.empty());
2616 return this->unique_prefix_;
2619 // Set the unique prefix to use before all exported symbols. This
2620 // comes from the command line option -fgo-prefix=XXX.
2623 Gogo::set_unique_prefix(const std::string& arg)
2625 go_assert(this->unique_prefix_.empty());
2626 this->unique_prefix_ = arg;
2627 this->unique_prefix_specified_ = true;
2630 // Work out the package priority. It is one more than the maximum
2631 // priority of an imported package.
2634 Gogo::package_priority() const
2637 for (Packages::const_iterator p = this->packages_.begin();
2638 p != this->packages_.end();
2640 if (p->second->priority() > priority)
2641 priority = p->second->priority();
2642 return priority + 1;
2645 // Export identifiers as requested.
2650 // For now we always stream to a section. Later we may want to
2651 // support streaming to a separate file.
2652 Stream_to_section stream;
2654 Export exp(&stream);
2655 exp.register_builtin_types(this);
2656 exp.export_globals(this->package_name(),
2657 this->unique_prefix(),
2658 this->package_priority(),
2659 (this->need_init_fn_ && !this->is_main_package()
2660 ? this->get_init_fn_name()
2662 this->imported_init_fns_,
2663 this->package_->bindings());
2666 // Find the blocks in order to convert named types defined in blocks.
2668 class Convert_named_types : public Traverse
2671 Convert_named_types(Gogo* gogo)
2672 : Traverse(traverse_blocks),
2678 block(Block* block);
2685 Convert_named_types::block(Block* block)
2687 this->gogo_->convert_named_types_in_bindings(block->bindings());
2688 return TRAVERSE_CONTINUE;
2691 // Convert all named types to the backend representation. Since named
2692 // types can refer to other types, this needs to be done in the right
2693 // sequence, which is handled by Named_type::convert. Here we arrange
2694 // to call that for each named type.
2697 Gogo::convert_named_types()
2699 this->convert_named_types_in_bindings(this->globals_);
2700 for (Packages::iterator p = this->packages_.begin();
2701 p != this->packages_.end();
2704 Package* package = p->second;
2705 this->convert_named_types_in_bindings(package->bindings());
2708 Convert_named_types cnt(this);
2709 this->traverse(&cnt);
2711 // Make all the builtin named types used for type descriptors, and
2712 // then convert them. They will only be written out if they are
2714 Type::make_type_descriptor_type();
2715 Type::make_type_descriptor_ptr_type();
2716 Function_type::make_function_type_descriptor_type();
2717 Pointer_type::make_pointer_type_descriptor_type();
2718 Struct_type::make_struct_type_descriptor_type();
2719 Array_type::make_array_type_descriptor_type();
2720 Array_type::make_slice_type_descriptor_type();
2721 Map_type::make_map_type_descriptor_type();
2722 Map_type::make_map_descriptor_type();
2723 Channel_type::make_chan_type_descriptor_type();
2724 Interface_type::make_interface_type_descriptor_type();
2725 Type::convert_builtin_named_types(this);
2727 Runtime::convert_types(this);
2729 Function_type::convert_types(this);
2731 this->named_types_are_converted_ = true;
2734 // Convert all names types in a set of bindings.
2737 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2739 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2740 p != bindings->end_definitions();
2743 if ((*p)->is_type())
2744 (*p)->type_value()->convert(this);
2750 Function::Function(Function_type* type, Function* enclosing, Block* block,
2751 source_location location)
2752 : type_(type), enclosing_(enclosing), results_(NULL),
2753 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2754 defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2755 is_recover_thunk_(false), has_recover_thunk_(false)
2759 // Create the named result variables.
2762 Function::create_result_variables(Gogo* gogo)
2764 const Typed_identifier_list* results = this->type_->results();
2765 if (results == NULL || results->empty())
2768 if (!results->front().name().empty())
2769 this->results_are_named_ = true;
2771 this->results_ = new Results();
2772 this->results_->reserve(results->size());
2774 Block* block = this->block_;
2776 for (Typed_identifier_list::const_iterator p = results->begin();
2777 p != results->end();
2780 std::string name = p->name();
2781 if (name.empty() || Gogo::is_sink_name(name))
2783 static int result_counter;
2785 snprintf(buf, sizeof buf, "$ret%d", result_counter);
2787 name = gogo->pack_hidden_name(buf, false);
2789 Result_variable* result = new Result_variable(p->type(), this, index,
2791 Named_object* no = block->bindings()->add_result_variable(name, result);
2792 if (no->is_result_variable())
2793 this->results_->push_back(no);
2796 static int dummy_result_count;
2798 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2799 ++dummy_result_count;
2800 name = gogo->pack_hidden_name(buf, false);
2801 no = block->bindings()->add_result_variable(name, result);
2802 go_assert(no->is_result_variable());
2803 this->results_->push_back(no);
2808 // Update the named result variables when cloning a function which
2812 Function::update_result_variables()
2814 if (this->results_ == NULL)
2817 for (Results::iterator p = this->results_->begin();
2818 p != this->results_->end();
2820 (*p)->result_var_value()->set_function(this);
2823 // Return the closure variable, creating it if necessary.
2826 Function::closure_var()
2828 if (this->closure_var_ == NULL)
2830 // We don't know the type of the variable yet. We add fields as
2832 source_location loc = this->type_->location();
2833 Struct_field_list* sfl = new Struct_field_list;
2834 Type* struct_type = Type::make_struct_type(sfl, loc);
2835 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2836 NULL, false, true, false, loc);
2837 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2838 // Note that the new variable is not in any binding contour.
2840 return this->closure_var_;
2843 // Set the type of the closure variable.
2846 Function::set_closure_type()
2848 if (this->closure_var_ == NULL)
2850 Named_object* closure = this->closure_var_;
2851 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2852 unsigned int index = 0;
2853 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2854 p != this->closure_fields_.end();
2857 Named_object* no = p->first;
2859 snprintf(buf, sizeof buf, "%u", index);
2860 std::string n = no->name() + buf;
2862 if (no->is_variable())
2863 var_type = no->var_value()->type();
2865 var_type = no->result_var_value()->type();
2866 Type* field_type = Type::make_pointer_type(var_type);
2867 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2871 // Return whether this function is a method.
2874 Function::is_method() const
2876 return this->type_->is_method();
2879 // Add a label definition.
2882 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
2883 source_location location)
2885 Label* lnull = NULL;
2886 std::pair<Labels::iterator, bool> ins =
2887 this->labels_.insert(std::make_pair(label_name, lnull));
2891 // This is a new label.
2892 label = new Label(label_name);
2893 ins.first->second = label;
2897 // The label was already in the hash table.
2898 label = ins.first->second;
2899 if (label->is_defined())
2901 error_at(location, "label %qs already defined",
2902 Gogo::message_name(label_name).c_str());
2903 inform(label->location(), "previous definition of %qs was here",
2904 Gogo::message_name(label_name).c_str());
2905 return new Label(label_name);
2909 label->define(location, gogo->bindings_snapshot(location));
2911 // Issue any errors appropriate for any previous goto's to this
2913 const std::vector<Bindings_snapshot*>& refs(label->refs());
2914 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
2917 (*p)->check_goto_to(gogo->current_block());
2918 label->clear_refs();
2923 // Add a reference to a label.
2926 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
2927 source_location location, bool issue_goto_errors)
2929 Label* lnull = NULL;
2930 std::pair<Labels::iterator, bool> ins =
2931 this->labels_.insert(std::make_pair(label_name, lnull));
2935 // The label was already in the hash table.
2936 label = ins.first->second;
2940 go_assert(ins.first->second == NULL);
2941 label = new Label(label_name);
2942 ins.first->second = label;
2945 label->set_is_used();
2947 if (issue_goto_errors)
2949 Bindings_snapshot* snapshot = label->snapshot();
2950 if (snapshot != NULL)
2951 snapshot->check_goto_from(gogo->current_block(), location);
2953 label->add_snapshot_ref(gogo->bindings_snapshot(location));
2959 // Warn about labels that are defined but not used.
2962 Function::check_labels() const
2964 for (Labels::const_iterator p = this->labels_.begin();
2965 p != this->labels_.end();
2968 Label* label = p->second;
2969 if (!label->is_used())
2970 error_at(label->location(), "label %qs defined and not used",
2971 Gogo::message_name(label->name()).c_str());
2975 // Swap one function with another. This is used when building the
2976 // thunk we use to call a function which calls recover. It may not
2977 // work for any other case.
2980 Function::swap_for_recover(Function *x)
2982 go_assert(this->enclosing_ == x->enclosing_);
2983 std::swap(this->results_, x->results_);
2984 std::swap(this->closure_var_, x->closure_var_);
2985 std::swap(this->block_, x->block_);
2986 go_assert(this->location_ == x->location_);
2987 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2988 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2991 // Traverse the tree.
2994 Function::traverse(Traverse* traverse)
2996 unsigned int traverse_mask = traverse->traverse_mask();
2999 & (Traverse::traverse_types | Traverse::traverse_expressions))
3002 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3003 return TRAVERSE_EXIT;
3006 // FIXME: We should check traverse_functions here if nested
3007 // functions are stored in block bindings.
3008 if (this->block_ != NULL
3010 & (Traverse::traverse_variables
3011 | Traverse::traverse_constants
3012 | Traverse::traverse_blocks
3013 | Traverse::traverse_statements
3014 | Traverse::traverse_expressions
3015 | Traverse::traverse_types)) != 0)
3017 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3018 return TRAVERSE_EXIT;
3021 return TRAVERSE_CONTINUE;
3024 // Work out types for unspecified variables and constants.
3027 Function::determine_types()
3029 if (this->block_ != NULL)
3030 this->block_->determine_types();
3033 // Get a pointer to the variable representing the defer stack for this
3034 // function, making it if necessary. The value of the variable is set
3035 // by the runtime routines to true if the function is returning,
3036 // rather than panicing through. A pointer to this variable is used
3037 // as a marker for the functions on the defer stack associated with
3038 // this function. A function-specific variable permits inlining a
3039 // function which uses defer.
3042 Function::defer_stack(source_location location)
3044 if (this->defer_stack_ == NULL)
3046 Type* t = Type::lookup_bool_type();
3047 Expression* n = Expression::make_boolean(false, location);
3048 this->defer_stack_ = Statement::make_temporary(t, n, location);
3049 this->defer_stack_->set_is_address_taken();
3051 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3053 return Expression::make_unary(OPERATOR_AND, ref, location);
3056 // Export the function.
3059 Function::export_func(Export* exp, const std::string& name) const
3061 Function::export_func_with_type(exp, name, this->type_);
3064 // Export a function with a type.
3067 Function::export_func_with_type(Export* exp, const std::string& name,
3068 const Function_type* fntype)
3070 exp->write_c_string("func ");
3072 if (fntype->is_method())
3074 exp->write_c_string("(");
3075 exp->write_type(fntype->receiver()->type());
3076 exp->write_c_string(") ");
3079 exp->write_string(name);
3081 exp->write_c_string(" (");
3082 const Typed_identifier_list* parameters = fntype->parameters();
3083 if (parameters != NULL)
3085 bool is_varargs = fntype->is_varargs();
3087 for (Typed_identifier_list::const_iterator p = parameters->begin();
3088 p != parameters->end();
3094 exp->write_c_string(", ");
3095 if (!is_varargs || p + 1 != parameters->end())
3096 exp->write_type(p->type());
3099 exp->write_c_string("...");
3100 exp->write_type(p->type()->array_type()->element_type());
3104 exp->write_c_string(")");
3106 const Typed_identifier_list* results = fntype->results();
3107 if (results != NULL)
3109 if (results->size() == 1)
3111 exp->write_c_string(" ");
3112 exp->write_type(results->begin()->type());
3116 exp->write_c_string(" (");
3118 for (Typed_identifier_list::const_iterator p = results->begin();
3119 p != results->end();
3125 exp->write_c_string(", ");
3126 exp->write_type(p->type());
3128 exp->write_c_string(")");
3131 exp->write_c_string(";\n");
3134 // Import a function.
3137 Function::import_func(Import* imp, std::string* pname,
3138 Typed_identifier** preceiver,
3139 Typed_identifier_list** pparameters,
3140 Typed_identifier_list** presults,
3143 imp->require_c_string("func ");
3146 if (imp->peek_char() == '(')
3148 imp->require_c_string("(");
3149 Type* rtype = imp->read_type();
3150 *preceiver = new Typed_identifier(Import::import_marker, rtype,
3152 imp->require_c_string(") ");
3155 *pname = imp->read_identifier();
3157 Typed_identifier_list* parameters;
3158 *is_varargs = false;
3159 imp->require_c_string(" (");
3160 if (imp->peek_char() == ')')
3164 parameters = new Typed_identifier_list();
3167 if (imp->match_c_string("..."))
3173 Type* ptype = imp->read_type();
3175 ptype = Type::make_array_type(ptype, NULL);
3176 parameters->push_back(Typed_identifier(Import::import_marker,
3177 ptype, imp->location()));
3178 if (imp->peek_char() != ',')
3180 go_assert(!*is_varargs);
3181 imp->require_c_string(", ");
3184 imp->require_c_string(")");
3185 *pparameters = parameters;
3187 Typed_identifier_list* results;
3188 if (imp->peek_char() != ' ')
3192 results = new Typed_identifier_list();
3193 imp->require_c_string(" ");
3194 if (imp->peek_char() != '(')
3196 Type* rtype = imp->read_type();
3197 results->push_back(Typed_identifier(Import::import_marker, rtype,
3202 imp->require_c_string("(");
3205 Type* rtype = imp->read_type();
3206 results->push_back(Typed_identifier(Import::import_marker,
3207 rtype, imp->location()));
3208 if (imp->peek_char() != ',')
3210 imp->require_c_string(", ");
3212 imp->require_c_string(")");
3215 imp->require_c_string(";\n");
3216 *presults = results;
3221 Block::Block(Block* enclosing, source_location location)
3222 : enclosing_(enclosing), statements_(),
3223 bindings_(new Bindings(enclosing == NULL
3225 : enclosing->bindings())),
3226 start_location_(location),
3227 end_location_(UNKNOWN_LOCATION)
3231 // Add a statement to a block.
3234 Block::add_statement(Statement* statement)
3236 this->statements_.push_back(statement);
3239 // Add a statement to the front of a block. This is slow but is only
3240 // used for reference counts of parameters.
3243 Block::add_statement_at_front(Statement* statement)
3245 this->statements_.insert(this->statements_.begin(), statement);
3248 // Replace a statement in a block.
3251 Block::replace_statement(size_t index, Statement* s)
3253 go_assert(index < this->statements_.size());
3254 this->statements_[index] = s;
3257 // Add a statement before another statement.
3260 Block::insert_statement_before(size_t index, Statement* s)
3262 go_assert(index < this->statements_.size());
3263 this->statements_.insert(this->statements_.begin() + index, s);
3266 // Add a statement after another statement.
3269 Block::insert_statement_after(size_t index, Statement* s)
3271 go_assert(index < this->statements_.size());
3272 this->statements_.insert(this->statements_.begin() + index + 1, s);
3275 // Traverse the tree.
3278 Block::traverse(Traverse* traverse)
3280 unsigned int traverse_mask = traverse->traverse_mask();
3282 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3284 int t = traverse->block(this);
3285 if (t == TRAVERSE_EXIT)
3286 return TRAVERSE_EXIT;
3287 else if (t == TRAVERSE_SKIP_COMPONENTS)
3288 return TRAVERSE_CONTINUE;
3292 & (Traverse::traverse_variables
3293 | Traverse::traverse_constants
3294 | Traverse::traverse_expressions
3295 | Traverse::traverse_types)) != 0)
3297 const unsigned int e_or_t = (Traverse::traverse_expressions
3298 | Traverse::traverse_types);
3299 const unsigned int e_or_t_or_s = (e_or_t
3300 | Traverse::traverse_statements);
3301 for (Bindings::const_definitions_iterator pb =
3302 this->bindings_->begin_definitions();
3303 pb != this->bindings_->end_definitions();
3306 int t = TRAVERSE_CONTINUE;
3307 switch ((*pb)->classification())
3309 case Named_object::NAMED_OBJECT_CONST:
3310 if ((traverse_mask & Traverse::traverse_constants) != 0)
3311 t = traverse->constant(*pb, false);
3312 if (t == TRAVERSE_CONTINUE
3313 && (traverse_mask & e_or_t) != 0)
3315 Type* tc = (*pb)->const_value()->type();
3317 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3318 return TRAVERSE_EXIT;
3319 t = (*pb)->const_value()->traverse_expression(traverse);
3323 case Named_object::NAMED_OBJECT_VAR:
3324 case Named_object::NAMED_OBJECT_RESULT_VAR:
3325 if ((traverse_mask & Traverse::traverse_variables) != 0)
3326 t = traverse->variable(*pb);
3327 if (t == TRAVERSE_CONTINUE
3328 && (traverse_mask & e_or_t) != 0)
3330 if ((*pb)->is_result_variable()
3331 || (*pb)->var_value()->has_type())
3333 Type* tv = ((*pb)->is_variable()
3334 ? (*pb)->var_value()->type()
3335 : (*pb)->result_var_value()->type());
3337 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3338 return TRAVERSE_EXIT;
3341 if (t == TRAVERSE_CONTINUE
3342 && (traverse_mask & e_or_t_or_s) != 0
3343 && (*pb)->is_variable())
3344 t = (*pb)->var_value()->traverse_expression(traverse,
3348 case Named_object::NAMED_OBJECT_FUNC:
3349 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3352 case Named_object::NAMED_OBJECT_TYPE:
3353 if ((traverse_mask & e_or_t) != 0)
3354 t = Type::traverse((*pb)->type_value(), traverse);
3357 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3358 case Named_object::NAMED_OBJECT_UNKNOWN:
3361 case Named_object::NAMED_OBJECT_PACKAGE:
3362 case Named_object::NAMED_OBJECT_SINK:
3369 if (t == TRAVERSE_EXIT)
3370 return TRAVERSE_EXIT;
3374 // No point in checking traverse_mask here--if we got here we always
3375 // want to walk the statements. The traversal can insert new
3376 // statements before or after the current statement. Inserting
3377 // statements before the current statement requires updating I via
3378 // the pointer; those statements will not be traversed. Any new
3379 // statements inserted after the current statement will be traversed
3381 for (size_t i = 0; i < this->statements_.size(); ++i)
3383 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3384 return TRAVERSE_EXIT;
3387 return TRAVERSE_CONTINUE;
3390 // Work out types for unspecified variables and constants.
3393 Block::determine_types()
3395 for (Bindings::const_definitions_iterator pb =
3396 this->bindings_->begin_definitions();
3397 pb != this->bindings_->end_definitions();
3400 if ((*pb)->is_variable())
3401 (*pb)->var_value()->determine_type();
3402 else if ((*pb)->is_const())
3403 (*pb)->const_value()->determine_type();
3406 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3407 ps != this->statements_.end();
3409 (*ps)->determine_types();
3412 // Return true if the statements in this block may fall through.
3415 Block::may_fall_through() const
3417 if (this->statements_.empty())
3419 return this->statements_.back()->may_fall_through();
3422 // Convert a block to the backend representation.
3425 Block::get_backend(Translate_context* context)
3427 Gogo* gogo = context->gogo();
3428 Named_object* function = context->function();
3429 std::vector<Bvariable*> vars;
3430 vars.reserve(this->bindings_->size_definitions());
3431 for (Bindings::const_definitions_iterator pv =
3432 this->bindings_->begin_definitions();
3433 pv != this->bindings_->end_definitions();
3436 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
3437 vars.push_back((*pv)->get_backend_variable(gogo, function));
3440 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
3441 // until we have a proper representation of the init function.
3442 Bfunction* bfunction;
3443 if (function == NULL)
3446 bfunction = tree_to_function(function->func_value()->get_decl());
3447 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
3448 vars, this->start_location_,
3449 this->end_location_);
3451 Translate_context subcontext(gogo, function, this, ret);
3452 std::vector<Bstatement*> bstatements;
3453 bstatements.reserve(this->statements_.size());
3454 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
3455 p != this->statements_.end();
3457 bstatements.push_back((*p)->get_backend(&subcontext));
3459 context->backend()->block_add_statements(ret, bstatements);
3464 // Class Bindings_snapshot.
3466 Bindings_snapshot::Bindings_snapshot(const Block* b, source_location location)
3467 : block_(b), counts_(), location_(location)
3471 this->counts_.push_back(b->bindings()->size_definitions());
3476 // Report errors appropriate for a goto from B to this.
3479 Bindings_snapshot::check_goto_from(const Block* b, source_location loc)
3482 if (!this->check_goto_block(loc, b, this->block_, &dummy))
3484 this->check_goto_defs(loc, this->block_,
3485 this->block_->bindings()->size_definitions(),
3489 // Report errors appropriate for a goto from this to B.
3492 Bindings_snapshot::check_goto_to(const Block* b)
3495 if (!this->check_goto_block(this->location_, this->block_, b, &index))
3497 this->check_goto_defs(this->location_, b, this->counts_[index],
3498 b->bindings()->size_definitions());
3501 // Report errors appropriate for a goto at LOC from BFROM to BTO.
3502 // Return true if all is well, false if we reported an error. If this
3503 // returns true, it sets *PINDEX to the number of blocks BTO is above
3507 Bindings_snapshot::check_goto_block(source_location loc, const Block* bfrom,
3508 const Block* bto, size_t* pindex)
3510 // It is an error if BTO is not either BFROM or above BFROM.
3512 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
3516 error_at(loc, "goto jumps into block");
3517 inform(bto->start_location(), "goto target block starts here");
3525 // Report errors appropriate for a goto at LOC ending at BLOCK, where
3526 // CFROM is the number of names defined at the point of the goto and
3527 // CTO is the number of names defined at the point of the label.
3530 Bindings_snapshot::check_goto_defs(source_location loc, const Block* block,
3531 size_t cfrom, size_t cto)
3535 Bindings::const_definitions_iterator p =
3536 block->bindings()->begin_definitions();
3537 for (size_t i = 0; i < cfrom; ++i)
3539 go_assert(p != block->bindings()->end_definitions());
3542 go_assert(p != block->bindings()->end_definitions());
3544 std::string n = (*p)->message_name();
3545 error_at(loc, "goto jumps over declaration of %qs", n.c_str());
3546 inform((*p)->location(), "%qs defined here", n.c_str());
3552 Variable::Variable(Type* type, Expression* init, bool is_global,
3553 bool is_parameter, bool is_receiver,
3554 source_location location)
3555 : type_(type), init_(init), preinit_(NULL), location_(location),
3556 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3557 is_receiver_(is_receiver), is_varargs_parameter_(false),
3558 is_address_taken_(false), is_non_escaping_address_taken_(false),
3559 seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
3560 type_from_range_index_(false), type_from_range_value_(false),
3561 type_from_chan_element_(false), is_type_switch_var_(false),
3562 determined_type_(false)
3564 go_assert(type != NULL || init != NULL);
3565 go_assert(!is_parameter || init == NULL);
3568 // Traverse the initializer expression.
3571 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
3573 if (this->preinit_ != NULL)
3575 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3576 return TRAVERSE_EXIT;
3578 if (this->init_ != NULL
3580 & (Traverse::traverse_expressions | Traverse::traverse_types))
3583 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3584 return TRAVERSE_EXIT;
3586 return TRAVERSE_CONTINUE;
3589 // Lower the initialization expression after parsing is complete.
3592 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
3593 Statement_inserter* inserter)
3595 if (this->init_ != NULL && !this->init_is_lowered_)
3599 // We will give an error elsewhere, this is just to prevent
3600 // an infinite loop.
3605 Statement_inserter global_inserter;
3606 if (this->is_global_)
3608 global_inserter = Statement_inserter(gogo, this);
3609 inserter = &global_inserter;
3612 gogo->lower_expression(function, inserter, &this->init_);
3614 this->seen_ = false;
3616 this->init_is_lowered_ = true;
3620 // Get the preinit block.
3623 Variable::preinit_block(Gogo* gogo)
3625 go_assert(this->is_global_);
3626 if (this->preinit_ == NULL)
3627 this->preinit_ = new Block(NULL, this->location());
3629 // If a global variable has a preinitialization statement, then we
3630 // need to have an initialization function.
3631 gogo->set_need_init_fn();
3633 return this->preinit_;
3636 // Add a statement to be run before the initialization expression.
3639 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3641 Block* b = this->preinit_block(gogo);
3642 b->add_statement(s);
3643 b->set_end_location(s->location());
3646 // In an assignment which sets a variable to a tuple of EXPR, return
3647 // the type of the first element of the tuple.
3650 Variable::type_from_tuple(Expression* expr, bool report_error) const
3652 if (expr->map_index_expression() != NULL)
3654 Map_type* mt = expr->map_index_expression()->get_map_type();
3656 return Type::make_error_type();
3657 return mt->val_type();
3659 else if (expr->receive_expression() != NULL)
3661 Expression* channel = expr->receive_expression()->channel();
3662 Type* channel_type = channel->type();
3663 if (channel_type->channel_type() == NULL)
3664 return Type::make_error_type();
3665 return channel_type->channel_type()->element_type();
3670 error_at(this->location(), "invalid tuple definition");
3671 return Type::make_error_type();
3675 // Given EXPR used in a range clause, return either the index type or
3676 // the value type of the range, depending upon GET_INDEX_TYPE.
3679 Variable::type_from_range(Expression* expr, bool get_index_type,
3680 bool report_error) const
3682 Type* t = expr->type();
3683 if (t->array_type() != NULL
3684 || (t->points_to() != NULL
3685 && t->points_to()->array_type() != NULL
3686 && !t->points_to()->is_slice_type()))
3689 return Type::lookup_integer_type("int");
3691 return t->deref()->array_type()->element_type();
3693 else if (t->is_string_type())
3694 return Type::lookup_integer_type("int");
3695 else if (t->map_type() != NULL)
3698 return t->map_type()->key_type();
3700 return t->map_type()->val_type();
3702 else if (t->channel_type() != NULL)
3705 return t->channel_type()->element_type();
3709 error_at(this->location(),
3710 "invalid definition of value variable for channel range");
3711 return Type::make_error_type();
3717 error_at(this->location(), "invalid type for range clause");
3718 return Type::make_error_type();
3722 // EXPR should be a channel. Return the channel's element type.
3725 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3727 Type* t = expr->type();
3728 if (t->channel_type() != NULL)
3729 return t->channel_type()->element_type();
3733 error_at(this->location(), "expected channel");
3734 return Type::make_error_type();
3738 // Return the type of the Variable. This may be called before
3739 // Variable::determine_type is called, which means that we may need to
3740 // get the type from the initializer. FIXME: If we combine lowering
3741 // with type determination, then this should be unnecessary.
3746 // A variable in a type switch with a nil case will have the wrong
3747 // type here. This gets fixed up in determine_type, below.
3748 Type* type = this->type_;
3749 Expression* init = this->init_;
3750 if (this->is_type_switch_var_
3751 && this->type_->is_nil_constant_as_type())
3753 Type_guard_expression* tge = this->init_->type_guard_expression();
3754 go_assert(tge != NULL);
3761 if (this->type_ == NULL || !this->type_->is_error_type())
3763 error_at(this->location_, "variable initializer refers to itself");
3764 this->type_ = Type::make_error_type();
3773 else if (this->type_from_init_tuple_)
3774 type = this->type_from_tuple(init, false);
3775 else if (this->type_from_range_index_ || this->type_from_range_value_)
3776 type = this->type_from_range(init, this->type_from_range_index_, false);
3777 else if (this->type_from_chan_element_)
3778 type = this->type_from_chan_element(init, false);
3781 go_assert(init != NULL);
3782 type = init->type();
3783 go_assert(type != NULL);
3785 // Variables should not have abstract types.
3786 if (type->is_abstract())
3787 type = type->make_non_abstract_type();
3789 if (type->is_void_type())
3790 type = Type::make_error_type();
3793 this->seen_ = false;
3798 // Fetch the type from a const pointer, in which case it should have
3799 // been set already.
3802 Variable::type() const
3804 go_assert(this->type_ != NULL);
3808 // Set the type if necessary.
3811 Variable::determine_type()
3813 if (this->determined_type_)
3815 this->determined_type_ = true;
3817 if (this->preinit_ != NULL)
3818 this->preinit_->determine_types();
3820 // A variable in a type switch with a nil case will have the wrong
3821 // type here. It will have an initializer which is a type guard.
3822 // We want to initialize it to the value without the type guard, and
3823 // use the type of that value as well.
3824 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3826 Type_guard_expression* tge = this->init_->type_guard_expression();
3827 go_assert(tge != NULL);
3829 this->init_ = tge->expr();
3832 if (this->init_ == NULL)
3833 go_assert(this->type_ != NULL && !this->type_->is_abstract());
3834 else if (this->type_from_init_tuple_)
3836 Expression *init = this->init_;
3837 init->determine_type_no_context();
3838 this->type_ = this->type_from_tuple(init, true);
3841 else if (this->type_from_range_index_ || this->type_from_range_value_)
3843 Expression* init = this->init_;
3844 init->determine_type_no_context();
3845 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3849 else if (this->type_from_chan_element_)
3851 Expression* init = this->init_;
3852 init->determine_type_no_context();
3853 this->type_ = this->type_from_chan_element(init, true);
3858 Type_context context(this->type_, false);
3859 this->init_->determine_type(&context);
3860 if (this->type_ == NULL)
3862 Type* type = this->init_->type();
3863 go_assert(type != NULL);
3864 if (type->is_abstract())
3865 type = type->make_non_abstract_type();
3867 if (type->is_void_type())
3869 error_at(this->location_, "variable has no type");
3870 type = Type::make_error_type();
3872 else if (type->is_nil_type())
3874 error_at(this->location_, "variable defined to nil type");
3875 type = Type::make_error_type();
3877 else if (type->is_call_multiple_result_type())
3879 error_at(this->location_,
3880 "single variable set to multiple value function call");
3881 type = Type::make_error_type();
3889 // Export the variable
3892 Variable::export_var(Export* exp, const std::string& name) const
3894 go_assert(this->is_global_);
3895 exp->write_c_string("var ");
3896 exp->write_string(name);
3897 exp->write_c_string(" ");
3898 exp->write_type(this->type());
3899 exp->write_c_string(";\n");
3902 // Import a variable.
3905 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3907 imp->require_c_string("var ");
3908 *pname = imp->read_identifier();
3909 imp->require_c_string(" ");
3910 *ptype = imp->read_type();
3911 imp->require_c_string(";\n");
3914 // Convert a variable to the backend representation.
3917 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
3918 const Package* package, const std::string& name)
3920 if (this->backend_ == NULL)
3922 Backend* backend = gogo->backend();
3923 Type* type = this->type_;
3924 if (type->is_error_type()
3925 || (type->is_undefined()
3926 && (!this->is_global_ || package == NULL)))
3927 this->backend_ = backend->error_variable();
3930 bool is_parameter = this->is_parameter_;
3931 if (this->is_receiver_ && type->points_to() == NULL)
3932 is_parameter = false;
3933 if (this->is_in_heap())
3935 is_parameter = false;
3936 type = Type::make_pointer_type(type);
3939 std::string n = Gogo::unpack_hidden_name(name);
3940 Btype* btype = type->get_backend(gogo);
3943 if (this->is_global_)
3944 bvar = backend->global_variable((package == NULL
3945 ? gogo->package_name()
3948 ? gogo->unique_prefix()
3949 : package->unique_prefix()),
3953 Gogo::is_hidden_name(name),
3957 tree fndecl = function->func_value()->get_decl();
3958 Bfunction* bfunction = tree_to_function(fndecl);
3959 bool is_address_taken = (this->is_non_escaping_address_taken_
3960 && !this->is_in_heap());
3962 bvar = backend->parameter_variable(bfunction, n, btype,
3966 bvar = backend->local_variable(bfunction, n, btype,
3970 this->backend_ = bvar;
3973 return this->backend_;
3976 // Class Result_variable.
3978 // Convert a result variable to the backend representation.
3981 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
3982 const std::string& name)
3984 if (this->backend_ == NULL)
3986 Backend* backend = gogo->backend();
3987 Type* type = this->type_;
3988 if (type->is_error())
3989 this->backend_ = backend->error_variable();
3992 if (this->is_in_heap())
3993 type = Type::make_pointer_type(type);
3994 Btype* btype = type->get_backend(gogo);
3995 tree fndecl = function->func_value()->get_decl();
3996 Bfunction* bfunction = tree_to_function(fndecl);
3997 std::string n = Gogo::unpack_hidden_name(name);
3998 bool is_address_taken = (this->is_non_escaping_address_taken_
3999 && !this->is_in_heap());
4000 this->backend_ = backend->local_variable(bfunction, n, btype,
4005 return this->backend_;
4008 // Class Named_constant.
4010 // Traverse the initializer expression.
4013 Named_constant::traverse_expression(Traverse* traverse)
4015 return Expression::traverse(&this->expr_, traverse);
4018 // Determine the type of the constant.
4021 Named_constant::determine_type()
4023 if (this->type_ != NULL)
4025 Type_context context(this->type_, false);
4026 this->expr_->determine_type(&context);
4030 // A constant may have an abstract type.
4031 Type_context context(NULL, true);
4032 this->expr_->determine_type(&context);
4033 this->type_ = this->expr_->type();
4034 go_assert(this->type_ != NULL);
4038 // Indicate that we found and reported an error for this constant.
4041 Named_constant::set_error()
4043 this->type_ = Type::make_error_type();
4044 this->expr_ = Expression::make_error(this->location_);
4047 // Export a constant.
4050 Named_constant::export_const(Export* exp, const std::string& name) const
4052 exp->write_c_string("const ");
4053 exp->write_string(name);
4054 exp->write_c_string(" ");
4055 if (!this->type_->is_abstract())
4057 exp->write_type(this->type_);
4058 exp->write_c_string(" ");
4060 exp->write_c_string("= ");
4061 this->expr()->export_expression(exp);
4062 exp->write_c_string(";\n");
4065 // Import a constant.
4068 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
4071 imp->require_c_string("const ");
4072 *pname = imp->read_identifier();
4073 imp->require_c_string(" ");
4074 if (imp->peek_char() == '=')
4078 *ptype = imp->read_type();
4079 imp->require_c_string(" ");
4081 imp->require_c_string("= ");
4082 *pexpr = Expression::import_expression(imp);
4083 imp->require_c_string(";\n");
4089 Type_declaration::add_method(const std::string& name, Function* function)
4091 Named_object* ret = Named_object::make_function(name, NULL, function);
4092 this->methods_.push_back(ret);
4096 // Add a method declaration.
4099 Type_declaration::add_method_declaration(const std::string& name,
4100 Function_type* type,
4101 source_location location)
4103 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
4105 this->methods_.push_back(ret);
4109 // Return whether any methods ere defined.
4112 Type_declaration::has_methods() const
4114 return !this->methods_.empty();
4117 // Define methods for the real type.
4120 Type_declaration::define_methods(Named_type* nt)
4122 for (Methods::const_iterator p = this->methods_.begin();
4123 p != this->methods_.end();
4125 nt->add_existing_method(*p);
4128 // We are using the type. Return true if we should issue a warning.
4131 Type_declaration::using_type()
4133 bool ret = !this->issued_warning_;
4134 this->issued_warning_ = true;
4138 // Class Unknown_name.
4140 // Set the real named object.
4143 Unknown_name::set_real_named_object(Named_object* no)
4145 go_assert(this->real_named_object_ == NULL);
4146 go_assert(!no->is_unknown());
4147 this->real_named_object_ = no;
4150 // Class Named_object.
4152 Named_object::Named_object(const std::string& name,
4153 const Package* package,
4154 Classification classification)
4155 : name_(name), package_(package), classification_(classification),
4158 if (Gogo::is_sink_name(name))
4159 go_assert(classification == NAMED_OBJECT_SINK);
4162 // Make an unknown name. This is used by the parser. The name must