OSDN Git Service

Don't crash when declaring methods on unknown name.
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / gogo.cc
1 // gogo.cc -- Go frontend parsed representation.
2
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.
6
7 #include "go-system.h"
8
9 #include "go-c.h"
10 #include "go-dump.h"
11 #include "lex.h"
12 #include "types.h"
13 #include "statements.h"
14 #include "expressions.h"
15 #include "dataflow.h"
16 #include "import.h"
17 #include "export.h"
18 #include "gogo.h"
19
20 // Class Gogo.
21
22 Gogo::Gogo(int int_type_size, int float_type_size, int pointer_size)
23   : package_(NULL),
24     functions_(),
25     globals_(new Bindings(NULL)),
26     imports_(),
27     imported_unsafe_(false),
28     packages_(),
29     map_descriptors_(NULL),
30     type_descriptor_decls_(NULL),
31     init_functions_(),
32     need_init_fn_(false),
33     init_fn_name_(),
34     imported_init_fns_(),
35     unique_prefix_(),
36     interface_types_()
37 {
38   const source_location loc = BUILTINS_LOCATION;
39
40   Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
41                                                    RUNTIME_TYPE_KIND_UINT8);
42   this->add_named_type(uint8_type);
43   this->add_named_type(Type::make_integer_type("uint16", true,  16,
44                                                RUNTIME_TYPE_KIND_UINT16));
45   this->add_named_type(Type::make_integer_type("uint32", true,  32,
46                                                RUNTIME_TYPE_KIND_UINT32));
47   this->add_named_type(Type::make_integer_type("uint64", true,  64,
48                                                RUNTIME_TYPE_KIND_UINT64));
49
50   this->add_named_type(Type::make_integer_type("int8",  false,   8,
51                                                RUNTIME_TYPE_KIND_INT8));
52   this->add_named_type(Type::make_integer_type("int16", false,  16,
53                                                RUNTIME_TYPE_KIND_INT16));
54   this->add_named_type(Type::make_integer_type("int32", false,  32,
55                                                RUNTIME_TYPE_KIND_INT32));
56   this->add_named_type(Type::make_integer_type("int64", false,  64,
57                                                RUNTIME_TYPE_KIND_INT64));
58
59   this->add_named_type(Type::make_float_type("float32", 32,
60                                              RUNTIME_TYPE_KIND_FLOAT32));
61   this->add_named_type(Type::make_float_type("float64", 64,
62                                              RUNTIME_TYPE_KIND_FLOAT64));
63
64   this->add_named_type(Type::make_complex_type("complex64", 64,
65                                                RUNTIME_TYPE_KIND_COMPLEX64));
66   this->add_named_type(Type::make_complex_type("complex128", 128,
67                                                RUNTIME_TYPE_KIND_COMPLEX128));
68
69   if (int_type_size < 32)
70     int_type_size = 32;
71   this->add_named_type(Type::make_integer_type("uint", true,
72                                                int_type_size,
73                                                RUNTIME_TYPE_KIND_UINT));
74   Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
75                                                  RUNTIME_TYPE_KIND_INT);
76   this->add_named_type(int_type);
77
78   // "byte" is an alias for "uint8".  Construct a Named_object which
79   // points to UINT8_TYPE.  Note that this breaks the normal pairing
80   // in which a Named_object points to a Named_type which points back
81   // to the same Named_object.
82   Named_object* byte_type = this->declare_type("byte", loc);
83   byte_type->set_type_value(uint8_type);
84
85   this->add_named_type(Type::make_integer_type("uintptr", true,
86                                                pointer_size,
87                                                RUNTIME_TYPE_KIND_UINTPTR));
88
89   this->add_named_type(Type::make_float_type("float", float_type_size,
90                                              RUNTIME_TYPE_KIND_FLOAT));
91
92   this->add_named_type(Type::make_complex_type("complex", float_type_size * 2,
93                                                RUNTIME_TYPE_KIND_COMPLEX));
94
95   this->add_named_type(Type::make_named_bool_type());
96
97   this->add_named_type(Type::make_named_string_type());
98
99   this->globals_->add_constant(Typed_identifier("true",
100                                                 Type::make_boolean_type(),
101                                                 loc),
102                                NULL,
103                                Expression::make_boolean(true, loc),
104                                0);
105   this->globals_->add_constant(Typed_identifier("false",
106                                                 Type::make_boolean_type(),
107                                                 loc),
108                                NULL,
109                                Expression::make_boolean(false, loc),
110                                0);
111
112   this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
113                                                 loc),
114                                NULL,
115                                Expression::make_nil(loc),
116                                0);
117
118   Type* abstract_int_type = Type::make_abstract_integer_type();
119   this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
120                                                 loc),
121                                NULL,
122                                Expression::make_iota(),
123                                0);
124
125   Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
126   new_type->set_is_varargs();
127   new_type->set_is_builtin();
128   this->globals_->add_function_declaration("new", NULL, new_type, loc);
129
130   Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
131   make_type->set_is_varargs();
132   make_type->set_is_builtin();
133   this->globals_->add_function_declaration("make", NULL, make_type, loc);
134
135   Typed_identifier_list* len_result = new Typed_identifier_list();
136   len_result->push_back(Typed_identifier("", int_type, loc));
137   Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
138                                                      loc);
139   len_type->set_is_builtin();
140   this->globals_->add_function_declaration("len", NULL, len_type, loc);
141
142   Typed_identifier_list* cap_result = new Typed_identifier_list();
143   cap_result->push_back(Typed_identifier("", int_type, loc));
144   Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
145                                                      loc);
146   cap_type->set_is_builtin();
147   this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
148
149   Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
150   print_type->set_is_varargs();
151   print_type->set_is_builtin();
152   this->globals_->add_function_declaration("print", NULL, print_type, loc);
153
154   print_type = Type::make_function_type(NULL, NULL, NULL, loc);
155   print_type->set_is_varargs();
156   print_type->set_is_builtin();
157   this->globals_->add_function_declaration("println", NULL, print_type, loc);
158
159   Type *empty = Type::make_interface_type(NULL, loc);
160   Typed_identifier_list* panic_parms = new Typed_identifier_list();
161   panic_parms->push_back(Typed_identifier("e", empty, loc));
162   Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
163                                                        NULL, loc);
164   panic_type->set_is_builtin();
165   this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
166
167   Typed_identifier_list* recover_result = new Typed_identifier_list();
168   recover_result->push_back(Typed_identifier("", empty, loc));
169   Function_type* recover_type = Type::make_function_type(NULL, NULL,
170                                                          recover_result,
171                                                          loc);
172   recover_type->set_is_builtin();
173   this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
174
175   Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
176   close_type->set_is_varargs();
177   close_type->set_is_builtin();
178   this->globals_->add_function_declaration("close", NULL, close_type, loc);
179
180   Typed_identifier_list* closed_result = new Typed_identifier_list();
181   closed_result->push_back(Typed_identifier("", Type::lookup_bool_type(),
182                                             loc));
183   Function_type* closed_type = Type::make_function_type(NULL, NULL,
184                                                         closed_result, loc);
185   closed_type->set_is_varargs();
186   closed_type->set_is_builtin();
187   this->globals_->add_function_declaration("closed", NULL, closed_type, loc);
188
189   Typed_identifier_list* copy_result = new Typed_identifier_list();
190   copy_result->push_back(Typed_identifier("", int_type, loc));
191   Function_type* copy_type = Type::make_function_type(NULL, NULL,
192                                                       copy_result, loc);
193   copy_type->set_is_varargs();
194   copy_type->set_is_builtin();
195   this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
196
197   Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
198   append_type->set_is_varargs();
199   append_type->set_is_builtin();
200   this->globals_->add_function_declaration("append", NULL, append_type, loc);
201
202   Function_type* cmplx_type = Type::make_function_type(NULL, NULL, NULL, loc);
203   cmplx_type->set_is_varargs();
204   cmplx_type->set_is_builtin();
205   this->globals_->add_function_declaration("cmplx", NULL, cmplx_type, loc);
206
207   Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
208   real_type->set_is_varargs();
209   real_type->set_is_builtin();
210   this->globals_->add_function_declaration("real", NULL, real_type, loc);
211
212   Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
213   imag_type->set_is_varargs();
214   imag_type->set_is_builtin();
215   this->globals_->add_function_declaration("imag", NULL, cmplx_type, loc);
216
217   this->define_builtin_function_trees();
218
219   // Declare "init", to ensure that it is not defined with parameters
220   // or return values.
221   this->declare_function("init",
222                          Type::make_function_type(NULL, NULL, NULL, loc),
223                          loc);
224 }
225
226 // Munge name for use in an error message.
227
228 std::string
229 Gogo::message_name(const std::string& name)
230 {
231   return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
232 }
233
234 // Get the package name.
235
236 const std::string&
237 Gogo::package_name() const
238 {
239   gcc_assert(this->package_ != NULL);
240   return this->package_->name();
241 }
242
243 // Set the package name.
244
245 void
246 Gogo::set_package_name(const std::string& package_name,
247                        source_location location)
248 {
249   if (this->package_ != NULL && this->package_->name() != package_name)
250     {
251       error_at(location, "expected package %<%s%>",
252                Gogo::message_name(this->package_->name()).c_str());
253       return;
254     }
255
256   // If the user did not specify a unique prefix, we always use "go".
257   // This in effect requires that the package name be unique.
258   if (this->unique_prefix_.empty())
259     this->unique_prefix_ = "go";
260
261   this->package_ = this->register_package(package_name, this->unique_prefix_,
262                                           location);
263
264   // We used to permit people to qualify symbols with the current
265   // package name (e.g., P.x), but we no longer do.
266   // this->globals_->add_package(package_name, this->package_);
267
268   if (package_name == "main")
269     {
270       // Declare "main" as a function which takes no parameters and
271       // returns no value.
272       this->declare_function("main",
273                              Type::make_function_type(NULL, NULL, NULL,
274                                                       BUILTINS_LOCATION),
275                              BUILTINS_LOCATION);
276     }
277 }
278
279 // Import a package.
280
281 void
282 Gogo::import_package(const std::string& filename,
283                      const std::string& local_name,
284                      bool is_local_name_exported,
285                      source_location location)
286 {
287   if (filename == "unsafe")
288     {
289       this->import_unsafe(local_name, is_local_name_exported, location);
290       return;
291     }
292
293   Imports::const_iterator p = this->imports_.find(filename);
294   if (p != this->imports_.end())
295     {
296       Package* package = p->second;
297       package->set_location(location);
298       package->set_is_imported();
299       std::string ln = local_name;
300       bool is_ln_exported = is_local_name_exported;
301       if (ln.empty())
302         {
303           ln = package->name();
304           is_ln_exported = Lex::is_exported_name(ln);
305         }
306       if (ln != ".")
307         {
308           ln = this->pack_hidden_name(ln, is_ln_exported);
309           this->package_->bindings()->add_package(ln, package);
310         }
311       else
312         {
313           Bindings* bindings = package->bindings();
314           for (Bindings::const_declarations_iterator p =
315                  bindings->begin_declarations();
316                p != bindings->end_declarations();
317                ++p)
318             this->add_named_object(p->second);
319         }
320       return;
321     }
322
323   Import::Stream* stream = Import::open_package(filename, location);
324   if (stream == NULL)
325     {
326       error_at(location, "import file %qs not found", filename.c_str());
327       return;
328     }
329
330   Import imp(stream, location);
331   imp.register_builtin_types(this);
332   Package* package = imp.import(this, local_name, is_local_name_exported);
333   this->imports_.insert(std::make_pair(filename, package));
334   package->set_is_imported();
335
336   delete stream;
337 }
338
339 // Add an import control function for an imported package to the list.
340
341 void
342 Gogo::add_import_init_fn(const std::string& package_name,
343                          const std::string& init_name, int prio)
344 {
345   for (std::set<Import_init>::const_iterator p =
346          this->imported_init_fns_.begin();
347        p != this->imported_init_fns_.end();
348        ++p)
349     {
350       if (p->init_name() == init_name
351           && (p->package_name() != package_name || p->priority() != prio))
352         {
353           error("duplicate package initialization name %qs",
354                 Gogo::message_name(init_name).c_str());
355           inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
356                  Gogo::message_name(p->package_name()).c_str(),
357                  p->priority());
358           inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
359                  Gogo::message_name(package_name).c_str(), prio);
360           return;
361         }
362     }
363
364   this->imported_init_fns_.insert(Import_init(package_name, init_name,
365                                               prio));
366 }
367
368 // Return whether we are at the global binding level.
369
370 bool
371 Gogo::in_global_scope() const
372 {
373   return this->functions_.empty();
374 }
375
376 // Return the current binding contour.
377
378 Bindings*
379 Gogo::current_bindings()
380 {
381   if (!this->functions_.empty())
382     return this->functions_.back().blocks.back()->bindings();
383   else if (this->package_ != NULL)
384     return this->package_->bindings();
385   else
386     return this->globals_;
387 }
388
389 const Bindings*
390 Gogo::current_bindings() const
391 {
392   if (!this->functions_.empty())
393     return this->functions_.back().blocks.back()->bindings();
394   else if (this->package_ != NULL)
395     return this->package_->bindings();
396   else
397     return this->globals_;
398 }
399
400 // Return the current block.
401
402 Block*
403 Gogo::current_block()
404 {
405   if (this->functions_.empty())
406     return NULL;
407   else
408     return this->functions_.back().blocks.back();
409 }
410
411 // Look up a name in the current binding contour.  If PFUNCTION is not
412 // NULL, set it to the function in which the name is defined, or NULL
413 // if the name is defined in global scope.
414
415 Named_object*
416 Gogo::lookup(const std::string& name, Named_object** pfunction) const
417 {
418   if (Gogo::is_sink_name(name))
419     return Named_object::make_sink();
420
421   for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
422        p != this->functions_.rend();
423        ++p)
424     {
425       Named_object* ret = p->blocks.back()->bindings()->lookup(name);
426       if (ret != NULL)
427         {
428           if (pfunction != NULL)
429             *pfunction = p->function;
430           return ret;
431         }
432     }
433
434   if (pfunction != NULL)
435     *pfunction = NULL;
436
437   if (this->package_ != NULL)
438     {
439       Named_object* ret = this->package_->bindings()->lookup(name);
440       if (ret != NULL)
441         {
442           if (ret->package() != NULL)
443             ret->package()->set_used();
444           return ret;
445         }
446     }
447
448   // We do not look in the global namespace.  If we did, the global
449   // namespace would effectively hide names which were defined in
450   // package scope which we have not yet seen.  Instead,
451   // define_global_names is called after parsing is over to connect
452   // undefined names at package scope with names defined at global
453   // scope.
454
455   return NULL;
456 }
457
458 // Look up a name in the current block, without searching enclosing
459 // blocks.
460
461 Named_object*
462 Gogo::lookup_in_block(const std::string& name) const
463 {
464   gcc_assert(!this->functions_.empty());
465   gcc_assert(!this->functions_.back().blocks.empty());
466   return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
467 }
468
469 // Look up a name in the global namespace.
470
471 Named_object*
472 Gogo::lookup_global(const char* name) const
473 {
474   return this->globals_->lookup(name);
475 }
476
477 // Add an imported package.
478
479 Package*
480 Gogo::add_imported_package(const std::string& real_name,
481                            const std::string& alias_arg,
482                            bool is_alias_exported,
483                            const std::string& unique_prefix,
484                            source_location location,
485                            bool* padd_to_globals)
486 {
487   // FIXME: Now that we compile packages as a whole, should we permit
488   // importing the current package?
489   if (this->package_name() == real_name
490       && this->unique_prefix() == unique_prefix)
491     {
492       *padd_to_globals = false;
493       if (!alias_arg.empty() && alias_arg != ".")
494         {
495           std::string alias = this->pack_hidden_name(alias_arg,
496                                                      is_alias_exported);
497           this->package_->bindings()->add_package(alias, this->package_);
498         }
499       return this->package_;
500     }
501   else if (alias_arg == ".")
502     {
503       *padd_to_globals = true;
504       return this->register_package(real_name, unique_prefix, location);
505     }
506   else if (alias_arg == "_")
507     {
508       Package* ret = this->register_package(real_name, unique_prefix, location);
509       ret->set_uses_sink_alias();
510       return ret;
511     }
512   else
513     {
514       *padd_to_globals = false;
515       std::string alias = alias_arg;
516       if (alias.empty())
517         {
518           alias = real_name;
519           is_alias_exported = Lex::is_exported_name(alias);
520         }
521       alias = this->pack_hidden_name(alias, is_alias_exported);
522       Named_object* no = this->add_package(real_name, alias, unique_prefix,
523                                            location);
524       if (!no->is_package())
525         return NULL;
526       return no->package_value();
527     }
528 }
529
530 // Add a package.
531
532 Named_object*
533 Gogo::add_package(const std::string& real_name, const std::string& alias,
534                   const std::string& unique_prefix, source_location location)
535 {
536   gcc_assert(this->in_global_scope());
537
538   // Register the package.  Note that we might have already seen it in
539   // an earlier import.
540   Package* package = this->register_package(real_name, unique_prefix, location);
541
542   return this->package_->bindings()->add_package(alias, package);
543 }
544
545 // Register a package.  This package may or may not be imported.  This
546 // returns the Package structure for the package, creating if it
547 // necessary.
548
549 Package*
550 Gogo::register_package(const std::string& package_name,
551                        const std::string& unique_prefix,
552                        source_location location)
553 {
554   gcc_assert(!unique_prefix.empty() && !package_name.empty());
555   std::string name = unique_prefix + '.' + package_name;
556   Package* package = NULL;
557   std::pair<Packages::iterator, bool> ins =
558     this->packages_.insert(std::make_pair(name, package));
559   if (!ins.second)
560     {
561       // We have seen this package name before.
562       package = ins.first->second;
563       gcc_assert(package != NULL);
564       gcc_assert(package->name() == package_name
565                  && package->unique_prefix() == unique_prefix);
566       if (package->location() == UNKNOWN_LOCATION)
567         package->set_location(location);
568     }
569   else
570     {
571       // First time we have seen this package name.
572       package = new Package(package_name, unique_prefix, location);
573       gcc_assert(ins.first->second == NULL);
574       ins.first->second = package;
575     }
576
577   return package;
578 }
579
580 // Start compiling a function.
581
582 Named_object*
583 Gogo::start_function(const std::string& name, Function_type* type,
584                      bool add_method_to_type, source_location location)
585 {
586   bool at_top_level = this->functions_.empty();
587
588   Block* block = new Block(NULL, location);
589
590   Function* enclosing = (at_top_level
591                          ? NULL
592                          : this->functions_.back().function->func_value());
593
594   Function* function = new Function(type, enclosing, block, location);
595
596   if (type->is_method())
597     {
598       const Typed_identifier* receiver = type->receiver();
599       Variable* this_param = new Variable(receiver->type(), NULL, false,
600                                           true, true, location);
601       std::string name = receiver->name();
602       if (name.empty())
603         {
604           // We need to give receivers a name since they wind up in
605           // DECL_ARGUMENTS.  FIXME.
606           static unsigned int count;
607           char buf[50];
608           snprintf(buf, sizeof buf, "r.%u", count);
609           ++count;
610           name = buf;
611         }
612       block->bindings()->add_variable(name, NULL, this_param);
613     }
614
615   const Typed_identifier_list* parameters = type->parameters();
616   bool is_varargs = type->is_varargs();
617   if (parameters != NULL)
618     {
619       for (Typed_identifier_list::const_iterator p = parameters->begin();
620            p != parameters->end();
621            ++p)
622         {
623           Variable* param = new Variable(p->type(), NULL, false, true, false,
624                                          location);
625           if (is_varargs && p + 1 == parameters->end())
626             param->set_is_varargs_parameter();
627
628           std::string name = p->name();
629           if (name.empty() || Gogo::is_sink_name(name))
630             {
631               // We need to give parameters a name since they wind up
632               // in DECL_ARGUMENTS.  FIXME.
633               static unsigned int count;
634               char buf[50];
635               snprintf(buf, sizeof buf, "p.%u", count);
636               ++count;
637               name = buf;
638             }
639           block->bindings()->add_variable(name, NULL, param);
640         }
641     }
642
643   function->create_named_result_variables(this);
644
645   const std::string* pname;
646   std::string nested_name;
647   if (!name.empty())
648     pname = &name;
649   else
650     {
651       // Invent a name for a nested function.
652       static int nested_count;
653       char buf[30];
654       snprintf(buf, sizeof buf, ".$nested%d", nested_count);
655       ++nested_count;
656       nested_name = buf;
657       pname = &nested_name;
658     }
659
660   Named_object* ret;
661   if (Gogo::is_sink_name(*pname))
662     ret = Named_object::make_sink();
663   else if (!type->is_method())
664     {
665       ret = this->package_->bindings()->add_function(*pname, NULL, function);
666       if (!ret->is_function())
667         {
668           // Redefinition error.
669           ret = Named_object::make_function(name, NULL, function);
670         }
671     }
672   else
673     {
674       if (!add_method_to_type)
675         ret = Named_object::make_function(name, NULL, function);
676       else
677         {
678           gcc_assert(at_top_level);
679           Type* rtype = type->receiver()->type();
680
681           // We want to look through the pointer created by the
682           // parser, without getting an error if the type is not yet
683           // defined.
684           if (rtype->classification() == Type::TYPE_POINTER)
685             rtype = rtype->points_to();
686
687           if (rtype->is_error_type())
688             ret = Named_object::make_function(name, NULL, function);
689           else if (rtype->named_type() != NULL)
690             {
691               ret = rtype->named_type()->add_method(name, function);
692               if (!ret->is_function())
693                 {
694                   // Redefinition error.
695                   ret = Named_object::make_function(name, NULL, function);
696                 }
697             }
698           else if (rtype->forward_declaration_type() != NULL)
699             {
700               Named_object* type_no =
701                 rtype->forward_declaration_type()->named_object();
702               if (type_no->is_unknown())
703                 {
704                   // If we are seeing methods it really must be a
705                   // type.  Declare it as such.  An alternative would
706                   // be to support lists of methods for unknown
707                   // expressions.  Either way the error messages if
708                   // this is not a type are going to get confusing.
709                   Named_object* declared =
710                     this->declare_package_type(type_no->name(),
711                                                type_no->location());
712                   gcc_assert(declared
713                              == type_no->unknown_value()->real_named_object());
714                 }
715               ret = rtype->forward_declaration_type()->add_method(name,
716                                                                   function);
717             }
718           else
719             gcc_unreachable();
720         }
721       this->package_->bindings()->add_method(ret);
722     }
723
724   this->functions_.resize(this->functions_.size() + 1);
725   Open_function& of(this->functions_.back());
726   of.function = ret;
727   of.blocks.push_back(block);
728
729   if (!type->is_method() && Gogo::unpack_hidden_name(name) == "init")
730     {
731       this->init_functions_.push_back(ret);
732       this->need_init_fn_ = true;
733     }
734
735   return ret;
736 }
737
738 // Finish compiling a function.
739
740 void
741 Gogo::finish_function(source_location location)
742 {
743   this->finish_block(location);
744   gcc_assert(this->functions_.back().blocks.empty());
745   this->functions_.pop_back();
746 }
747
748 // Return the current function.
749
750 Named_object*
751 Gogo::current_function() const
752 {
753   gcc_assert(!this->functions_.empty());
754   return this->functions_.back().function;
755 }
756
757 // Start a new block.
758
759 void
760 Gogo::start_block(source_location location)
761 {
762   gcc_assert(!this->functions_.empty());
763   Block* block = new Block(this->current_block(), location);
764   this->functions_.back().blocks.push_back(block);
765 }
766
767 // Finish a block.
768
769 Block*
770 Gogo::finish_block(source_location location)
771 {
772   gcc_assert(!this->functions_.empty());
773   gcc_assert(!this->functions_.back().blocks.empty());
774   Block* block = this->functions_.back().blocks.back();
775   this->functions_.back().blocks.pop_back();
776   block->set_end_location(location);
777   return block;
778 }
779
780 // Add an unknown name.
781
782 Named_object*
783 Gogo::add_unknown_name(const std::string& name, source_location location)
784 {
785   return this->package_->bindings()->add_unknown_name(name, location);
786 }
787
788 // Declare a function.
789
790 Named_object*
791 Gogo::declare_function(const std::string& name, Function_type* type,
792                        source_location location)
793 {
794   if (!type->is_method())
795     return this->current_bindings()->add_function_declaration(name, NULL, type,
796                                                               location);
797   else
798     {
799       // We don't bother to add this to the list of global
800       // declarations.
801       Type* rtype = type->receiver()->type();
802
803       // We want to look through the pointer created by the
804       // parser, without getting an error if the type is not yet
805       // defined.
806       if (rtype->classification() == Type::TYPE_POINTER)
807         rtype = rtype->points_to();
808
809       if (rtype->is_error_type())
810         return NULL;
811       else if (rtype->named_type() != NULL)
812         return rtype->named_type()->add_method_declaration(name, NULL, type,
813                                                            location);
814       else if (rtype->forward_declaration_type() != NULL)
815         {
816           Forward_declaration_type* ftype = rtype->forward_declaration_type();
817           return ftype->add_method_declaration(name, type, location);
818         }
819       else
820         gcc_unreachable();
821     }
822 }
823
824 // Add a label definition.
825
826 Label*
827 Gogo::add_label_definition(const std::string& label_name,
828                            source_location location)
829 {
830   gcc_assert(!this->functions_.empty());
831   Function* func = this->functions_.back().function->func_value();
832   Label* label = func->add_label_definition(label_name, location);
833   this->add_statement(Statement::make_label_statement(label, location));
834   return label;
835 }
836
837 // Add a label reference.
838
839 Label*
840 Gogo::add_label_reference(const std::string& label_name)
841 {
842   gcc_assert(!this->functions_.empty());
843   Function* func = this->functions_.back().function->func_value();
844   return func->add_label_reference(label_name);
845 }
846
847 // Add a statement.
848
849 void
850 Gogo::add_statement(Statement* statement)
851 {
852   gcc_assert(!this->functions_.empty()
853              && !this->functions_.back().blocks.empty());
854   this->functions_.back().blocks.back()->add_statement(statement);
855 }
856
857 // Add a block.
858
859 void
860 Gogo::add_block(Block* block, source_location location)
861 {
862   gcc_assert(!this->functions_.empty()
863              && !this->functions_.back().blocks.empty());
864   Statement* statement = Statement::make_block_statement(block, location);
865   this->functions_.back().blocks.back()->add_statement(statement);
866 }
867
868 // Add a constant.
869
870 Named_object*
871 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
872                    int iota_value)
873 {
874   return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
875 }
876
877 // Add a type.
878
879 void
880 Gogo::add_type(const std::string& name, Type* type, source_location location)
881 {
882   Named_object* no = this->current_bindings()->add_type(name, NULL, type,
883                                                         location);
884   if (!this->in_global_scope() && no->is_type())
885     no->type_value()->set_in_function(this->functions_.back().function);
886 }
887
888 // Add a named type.
889
890 void
891 Gogo::add_named_type(Named_type* type)
892 {
893   gcc_assert(this->in_global_scope());
894   this->current_bindings()->add_named_type(type);
895 }
896
897 // Declare a type.
898
899 Named_object*
900 Gogo::declare_type(const std::string& name, source_location location)
901 {
902   Bindings* bindings = this->current_bindings();
903   Named_object* no = bindings->add_type_declaration(name, NULL, location);
904   if (!this->in_global_scope() && no->is_type_declaration())
905     {
906       Named_object* f = this->functions_.back().function;
907       no->type_declaration_value()->set_in_function(f);
908     }
909   return no;
910 }
911
912 // Declare a type at the package level.
913
914 Named_object*
915 Gogo::declare_package_type(const std::string& name, source_location location)
916 {
917   return this->package_->bindings()->add_type_declaration(name, NULL, location);
918 }
919
920 // Define a type which was already declared.
921
922 void
923 Gogo::define_type(Named_object* no, Named_type* type)
924 {
925   this->current_bindings()->define_type(no, type);
926 }
927
928 // Add a variable.
929
930 Named_object*
931 Gogo::add_variable(const std::string& name, Variable* variable)
932 {
933   Named_object* no = this->current_bindings()->add_variable(name, NULL,
934                                                             variable);
935
936   // In a function the middle-end wants to see a DECL_EXPR node.
937   if (no != NULL
938       && no->is_variable()
939       && !no->var_value()->is_parameter()
940       && !this->functions_.empty())
941     this->add_statement(Statement::make_variable_declaration(no));
942
943   return no;
944 }
945
946 // Add a sink--a reference to the blank identifier _.
947
948 Named_object*
949 Gogo::add_sink()
950 {
951   return Named_object::make_sink();
952 }
953
954 // Add a named object.
955
956 void
957 Gogo::add_named_object(Named_object* no)
958 {
959   this->current_bindings()->add_named_object(no);
960 }
961
962 // Record that we've seen an interface type.
963
964 void
965 Gogo::record_interface_type(Interface_type* itype)
966 {
967   this->interface_types_.push_back(itype);
968 }
969
970 // Return a name for a thunk object.
971
972 std::string
973 Gogo::thunk_name()
974 {
975   static int thunk_count;
976   char thunk_name[50];
977   snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
978   ++thunk_count;
979   return thunk_name;
980 }
981
982 // Return whether a function is a thunk.
983
984 bool
985 Gogo::is_thunk(const Named_object* no)
986 {
987   return no->name().compare(0, 6, "$thunk") == 0;
988 }
989
990 // Define the global names.  We do this only after parsing all the
991 // input files, because the program might define the global names
992 // itself.
993
994 void
995 Gogo::define_global_names()
996 {
997   for (Bindings::const_declarations_iterator p =
998          this->globals_->begin_declarations();
999        p != this->globals_->end_declarations();
1000        ++p)
1001     {
1002       Named_object* global_no = p->second;
1003       std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1004       Named_object* no = this->package_->bindings()->lookup(name);
1005       if (no == NULL)
1006         continue;
1007       no = no->resolve();
1008       if (no->is_type_declaration())
1009         {
1010           if (global_no->is_type())
1011             {
1012               if (no->type_declaration_value()->has_methods())
1013                 error_at(no->location(),
1014                          "may not define methods for global type");
1015               no->set_type_value(global_no->type_value());
1016             }
1017           else
1018             {
1019               error_at(no->location(), "expected type");
1020               Type* errtype = Type::make_error_type();
1021               Named_object* err = Named_object::make_type("error", NULL,
1022                                                           errtype,
1023                                                           BUILTINS_LOCATION);
1024               no->set_type_value(err->type_value());
1025             }
1026         }
1027       else if (no->is_unknown())
1028         no->unknown_value()->set_real_named_object(global_no);
1029     }
1030 }
1031
1032 // Clear out names in file scope.
1033
1034 void
1035 Gogo::clear_file_scope()
1036 {
1037   this->package_->bindings()->clear_file_scope();
1038
1039   // Warn about packages which were imported but not used.
1040   for (Packages::iterator p = this->packages_.begin();
1041        p != this->packages_.end();
1042        ++p)
1043     {
1044       Package* package = p->second;
1045       if (package != this->package_
1046           && package->is_imported()
1047           && !package->used()
1048           && !package->uses_sink_alias()
1049           && !saw_errors())
1050         error_at(package->location(), "imported and not used: %s",
1051                  Gogo::message_name(package->name()).c_str());
1052       package->clear_is_imported();
1053       package->clear_uses_sink_alias();
1054       package->clear_used();
1055     }
1056 }
1057
1058 // Traverse the tree.
1059
1060 void
1061 Gogo::traverse(Traverse* traverse)
1062 {
1063   // Traverse the current package first for consistency.  The other
1064   // packages will only contain imported types, constants, and
1065   // declarations.
1066   if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1067     return;
1068   for (Packages::const_iterator p = this->packages_.begin();
1069        p != this->packages_.end();
1070        ++p)
1071     {
1072       if (p->second != this->package_)
1073         {
1074           if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1075             break;
1076         }
1077     }
1078 }
1079
1080 // Traversal class used to verify types.
1081
1082 class Verify_types : public Traverse
1083 {
1084  public:
1085   Verify_types()
1086     : Traverse(traverse_types)
1087   { }
1088
1089   int
1090   type(Type*);
1091 };
1092
1093 // Verify that a type is correct.
1094
1095 int
1096 Verify_types::type(Type* t)
1097 {
1098   // Don't verify types defined in other packages.
1099   Named_type* nt = t->named_type();
1100   if (nt != NULL && nt->named_object()->package() != NULL)
1101     return TRAVERSE_SKIP_COMPONENTS;
1102
1103   if (!t->verify())
1104     return TRAVERSE_SKIP_COMPONENTS;
1105   return TRAVERSE_CONTINUE;
1106 }
1107
1108 // Verify that all types are correct.
1109
1110 void
1111 Gogo::verify_types()
1112 {
1113   Verify_types traverse;
1114   this->traverse(&traverse);
1115 }
1116
1117 // Traversal class used to lower parse tree.
1118
1119 class Lower_parse_tree : public Traverse
1120 {
1121  public:
1122   Lower_parse_tree(Gogo* gogo, Named_object* function)
1123     : Traverse(traverse_constants
1124                | traverse_functions
1125                | traverse_statements
1126                | traverse_expressions),
1127       gogo_(gogo), function_(function), iota_value_(-1)
1128   { }
1129
1130   int
1131   constant(Named_object*, bool);
1132
1133   int
1134   function(Named_object*);
1135
1136   int
1137   statement(Block*, size_t* pindex, Statement*);
1138
1139   int
1140   expression(Expression**);
1141
1142  private:
1143   // General IR.
1144   Gogo* gogo_;
1145   // The function we are traversing.
1146   Named_object* function_;
1147   // Value to use for the predeclared constant iota.
1148   int iota_value_;
1149 };
1150
1151 // Lower constants.  We handle constants specially so that we can set
1152 // the right value for the predeclared constant iota.  This works in
1153 // conjunction with the way we lower Const_expression objects.
1154
1155 int
1156 Lower_parse_tree::constant(Named_object* no, bool)
1157 {
1158   Named_constant* nc = no->const_value();
1159
1160   // We can recursively a constant if the initializer expression
1161   // manages to refer to itself.
1162   if (nc->lowering())
1163     return TRAVERSE_CONTINUE;
1164   nc->set_lowering();
1165
1166   gcc_assert(this->iota_value_ == -1);
1167   this->iota_value_ = nc->iota_value();
1168   nc->traverse_expression(this);
1169   this->iota_value_ = -1;
1170
1171   nc->clear_lowering();
1172
1173   // We will traverse the expression a second time, but that will be
1174   // fast.
1175
1176   return TRAVERSE_CONTINUE;
1177 }
1178
1179 // Lower function closure types.  Record the function while lowering
1180 // it, so that we can pass it down when lowering an expression.
1181
1182 int
1183 Lower_parse_tree::function(Named_object* no)
1184 {
1185   no->func_value()->set_closure_type();
1186
1187   gcc_assert(this->function_ == NULL);
1188   this->function_ = no;
1189   int t = no->func_value()->traverse(this);
1190   this->function_ = NULL;
1191
1192   if (t == TRAVERSE_EXIT)
1193     return t;
1194   return TRAVERSE_SKIP_COMPONENTS;
1195 }
1196
1197 // Lower statement parse trees.
1198
1199 int
1200 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1201 {
1202   // Lower the expressions first.
1203   int t = sorig->traverse_contents(this);
1204   if (t == TRAVERSE_EXIT)
1205     return t;
1206
1207   // Keep lowering until nothing changes.
1208   Statement* s = sorig;
1209   while (true)
1210     {
1211       Statement* snew = s->lower(this->gogo_, block);
1212       if (snew == s)
1213         break;
1214       s = snew;
1215       t = s->traverse_contents(this);
1216       if (t == TRAVERSE_EXIT)
1217         return t;
1218     }
1219
1220   if (s != sorig)
1221     block->replace_statement(*pindex, s);
1222
1223   return TRAVERSE_SKIP_COMPONENTS;
1224 }
1225
1226 // Lower expression parse trees.
1227
1228 int
1229 Lower_parse_tree::expression(Expression** pexpr)
1230 {
1231   // We have to lower all subexpressions first, so that we can get
1232   // their type if necessary.  This is awkward, because we don't have
1233   // a postorder traversal pass.
1234   if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1235     return TRAVERSE_EXIT;
1236   // Keep lowering until nothing changes.
1237   while (true)
1238     {
1239       Expression* e = *pexpr;
1240       Expression* enew = e->lower(this->gogo_, this->function_,
1241                                   this->iota_value_);
1242       if (enew == e)
1243         break;
1244       *pexpr = enew;
1245     }
1246   return TRAVERSE_SKIP_COMPONENTS;
1247 }
1248
1249 // Lower the parse tree.  This is called after the parse is complete,
1250 // when all names should be resolved.
1251
1252 void
1253 Gogo::lower_parse_tree()
1254 {
1255   Lower_parse_tree lower_parse_tree(this, NULL);
1256   this->traverse(&lower_parse_tree);
1257 }
1258
1259 // Lower an expression.
1260
1261 void
1262 Gogo::lower_expression(Named_object* function, Expression** pexpr)
1263 {
1264   Lower_parse_tree lower_parse_tree(this, function);
1265   lower_parse_tree.expression(pexpr);
1266 }
1267
1268 // Lower a constant.  This is called when lowering a reference to a
1269 // constant.  We have to make sure that the constant has already been
1270 // lowered.
1271
1272 void
1273 Gogo::lower_constant(Named_object* no)
1274 {
1275   gcc_assert(no->is_const());
1276   Lower_parse_tree lower(this, NULL);
1277   lower.constant(no, false);
1278 }
1279
1280 // Look for interface types to finalize methods of inherited
1281 // interfaces.
1282
1283 class Finalize_methods : public Traverse
1284 {
1285  public:
1286   Finalize_methods(Gogo* gogo)
1287     : Traverse(traverse_types),
1288       gogo_(gogo)
1289   { }
1290
1291   int
1292   type(Type*);
1293
1294  private:
1295   Gogo* gogo_;
1296 };
1297
1298 // Finalize the methods of an interface type.
1299
1300 int
1301 Finalize_methods::type(Type* t)
1302 {
1303   // Check the classification so that we don't finalize the methods
1304   // twice for a named interface type.
1305   switch (t->classification())
1306     {
1307     case Type::TYPE_INTERFACE:
1308       t->interface_type()->finalize_methods();
1309       break;
1310
1311     case Type::TYPE_NAMED:
1312       {
1313         // We have to finalize the methods of the real type first.
1314         // But if the real type is a struct type, then we only want to
1315         // finalize the methods of the field types, not of the struct
1316         // type itself.  We don't want to add methods to the struct,
1317         // since it has a name.
1318         Type* rt = t->named_type()->real_type();
1319         if (rt->classification() != Type::TYPE_STRUCT)
1320           {
1321             if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1322               return TRAVERSE_EXIT;
1323           }
1324         else
1325           {
1326             if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1327               return TRAVERSE_EXIT;
1328           }
1329
1330         t->named_type()->finalize_methods(this->gogo_);
1331
1332         return TRAVERSE_SKIP_COMPONENTS;
1333       }
1334
1335     case Type::TYPE_STRUCT:
1336       t->struct_type()->finalize_methods(this->gogo_);
1337       break;
1338
1339     default:
1340       break;
1341     }
1342
1343   return TRAVERSE_CONTINUE;
1344 }
1345
1346 // Finalize method lists and build stub methods for types.
1347
1348 void
1349 Gogo::finalize_methods()
1350 {
1351   Finalize_methods finalize(this);
1352   this->traverse(&finalize);
1353 }
1354
1355 // Set types for unspecified variables and constants.
1356
1357 void
1358 Gogo::determine_types()
1359 {
1360   Bindings* bindings = this->current_bindings();
1361   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1362        p != bindings->end_definitions();
1363        ++p)
1364     {
1365       if ((*p)->is_function())
1366         (*p)->func_value()->determine_types();
1367       else if ((*p)->is_variable())
1368         (*p)->var_value()->determine_type();
1369       else if ((*p)->is_const())
1370         (*p)->const_value()->determine_type();
1371
1372       // See if a variable requires us to build an initialization
1373       // function.  We know that we will see all global variables
1374       // here.
1375       if (!this->need_init_fn_ && (*p)->is_variable())
1376         {
1377           Variable* variable = (*p)->var_value();
1378
1379           // If this is a global variable which requires runtime
1380           // initialization, we need an initialization function.
1381           if (!variable->is_global() || variable->init() == NULL)
1382             ;
1383           else if (variable->type()->interface_type() != NULL)
1384             this->need_init_fn_ = true;
1385           else if (variable->init()->is_constant())
1386             ;
1387           else if (!variable->init()->is_composite_literal())
1388             this->need_init_fn_ = true;
1389           else if (variable->init()->is_nonconstant_composite_literal())
1390             this->need_init_fn_ = true;
1391
1392           // If this is a global variable which holds a pointer value,
1393           // then we need an initialization function to register it as a
1394           // GC root.
1395           if (variable->is_global() && variable->type()->has_pointer())
1396             this->need_init_fn_ = true;
1397         }
1398     }
1399
1400   // Determine the types of constants in packages.
1401   for (Packages::const_iterator p = this->packages_.begin();
1402        p != this->packages_.end();
1403        ++p)
1404     p->second->determine_types();
1405 }
1406
1407 // Traversal class used for type checking.
1408
1409 class Check_types_traverse : public Traverse
1410 {
1411  public:
1412   Check_types_traverse(Gogo* gogo)
1413     : Traverse(traverse_variables
1414                | traverse_constants
1415                | traverse_statements
1416                | traverse_expressions),
1417       gogo_(gogo)
1418   { }
1419
1420   int
1421   variable(Named_object*);
1422
1423   int
1424   constant(Named_object*, bool);
1425
1426   int
1427   statement(Block*, size_t* pindex, Statement*);
1428
1429   int
1430   expression(Expression**);
1431
1432  private:
1433   // General IR.
1434   Gogo* gogo_;
1435 };
1436
1437 // Check that a variable initializer has the right type.
1438
1439 int
1440 Check_types_traverse::variable(Named_object* named_object)
1441 {
1442   if (named_object->is_variable())
1443     {
1444       Variable* var = named_object->var_value();
1445       Expression* init = var->init();
1446       std::string reason;
1447       if (init != NULL
1448           && !Type::are_assignable(var->type(), init->type(), &reason))
1449         {
1450           if (reason.empty())
1451             error_at(var->location(), "incompatible type in initialization");
1452           else
1453             error_at(var->location(),
1454                      "incompatible type in initialization (%s)",
1455                      reason.c_str());
1456           var->clear_init();
1457         }
1458     }
1459   return TRAVERSE_CONTINUE;
1460 }
1461
1462 // Check that a constant initializer has the right type.
1463
1464 int
1465 Check_types_traverse::constant(Named_object* named_object, bool)
1466 {
1467   Named_constant* constant = named_object->const_value();
1468   Type* ctype = constant->type();
1469   if (ctype->integer_type() == NULL
1470       && ctype->float_type() == NULL
1471       && ctype->complex_type() == NULL
1472       && !ctype->is_boolean_type()
1473       && !ctype->is_string_type())
1474     {
1475       if (!ctype->is_error_type())
1476         error_at(constant->location(), "invalid constant type");
1477       constant->set_error();
1478     }
1479   else if (!constant->expr()->is_constant())
1480     {
1481       error_at(constant->expr()->location(), "expression is not constant");
1482       constant->set_error();
1483     }
1484   else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1485                                  NULL))
1486     {
1487       error_at(constant->location(),
1488                "initialization expression has wrong type");
1489       constant->set_error();
1490     }
1491   return TRAVERSE_CONTINUE;
1492 }
1493
1494 // Check that types are valid in a statement.
1495
1496 int
1497 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1498 {
1499   s->check_types(this->gogo_);
1500   return TRAVERSE_CONTINUE;
1501 }
1502
1503 // Check that types are valid in an expression.
1504
1505 int
1506 Check_types_traverse::expression(Expression** expr)
1507 {
1508   (*expr)->check_types(this->gogo_);
1509   return TRAVERSE_CONTINUE;
1510 }
1511
1512 // Check that types are valid.
1513
1514 void
1515 Gogo::check_types()
1516 {
1517   Check_types_traverse traverse(this);
1518   this->traverse(&traverse);
1519 }
1520
1521 // Check the types in a single block.
1522
1523 void
1524 Gogo::check_types_in_block(Block* block)
1525 {
1526   Check_types_traverse traverse(this);
1527   block->traverse(&traverse);
1528 }
1529
1530 // A traversal class used to find a single shortcut operator within an
1531 // expression.
1532
1533 class Find_shortcut : public Traverse
1534 {
1535  public:
1536   Find_shortcut()
1537     : Traverse(traverse_blocks
1538                | traverse_statements
1539                | traverse_expressions),
1540       found_(NULL)
1541   { }
1542
1543   // A pointer to the expression which was found, or NULL if none was
1544   // found.
1545   Expression**
1546   found() const
1547   { return this->found_; }
1548
1549  protected:
1550   int
1551   block(Block*)
1552   { return TRAVERSE_SKIP_COMPONENTS; }
1553
1554   int
1555   statement(Block*, size_t*, Statement*)
1556   { return TRAVERSE_SKIP_COMPONENTS; }
1557
1558   int
1559   expression(Expression**);
1560
1561  private:
1562   Expression** found_;
1563 };
1564
1565 // Find a shortcut expression.
1566
1567 int
1568 Find_shortcut::expression(Expression** pexpr)
1569 {
1570   Expression* expr = *pexpr;
1571   Binary_expression* be = expr->binary_expression();
1572   if (be == NULL)
1573     return TRAVERSE_CONTINUE;
1574   Operator op = be->op();
1575   if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1576     return TRAVERSE_CONTINUE;
1577   gcc_assert(this->found_ == NULL);
1578   this->found_ = pexpr;
1579   return TRAVERSE_EXIT;
1580 }
1581
1582 // A traversal class used to turn shortcut operators into explicit if
1583 // statements.
1584
1585 class Shortcuts : public Traverse
1586 {
1587  public:
1588   Shortcuts()
1589     : Traverse(traverse_variables
1590                | traverse_statements)
1591   { }
1592
1593  protected:
1594   int
1595   variable(Named_object*);
1596
1597   int
1598   statement(Block*, size_t*, Statement*);
1599
1600  private:
1601   // Convert a shortcut operator.
1602   Statement*
1603   convert_shortcut(Block* enclosing, Expression** pshortcut);
1604 };
1605
1606 // Remove shortcut operators in a single statement.
1607
1608 int
1609 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1610 {
1611   // FIXME: This approach doesn't work for switch statements, because
1612   // we add the new statements before the whole switch when we need to
1613   // instead add them just before the switch expression.  The right
1614   // fix is probably to lower switch statements with nonconstant cases
1615   // to a series of conditionals.
1616   if (s->switch_statement() != NULL)
1617     return TRAVERSE_CONTINUE;
1618
1619   while (true)
1620     {
1621       Find_shortcut find_shortcut;
1622
1623       // If S is a variable declaration, then ordinary traversal won't
1624       // do anything.  We want to explicitly traverse the
1625       // initialization expression if there is one.
1626       Variable_declaration_statement* vds = s->variable_declaration_statement();
1627       Expression* init = NULL;
1628       if (vds == NULL)
1629         s->traverse_contents(&find_shortcut);
1630       else
1631         {
1632           init = vds->var()->var_value()->init();
1633           if (init == NULL)
1634             return TRAVERSE_CONTINUE;
1635           init->traverse(&init, &find_shortcut);
1636         }
1637       Expression** pshortcut = find_shortcut.found();
1638       if (pshortcut == NULL)
1639         return TRAVERSE_CONTINUE;
1640
1641       Statement* snew = this->convert_shortcut(block, pshortcut);
1642       block->insert_statement_before(*pindex, snew);
1643       ++*pindex;
1644
1645       if (pshortcut == &init)
1646         vds->var()->var_value()->set_init(init);
1647     }
1648 }
1649
1650 // Remove shortcut operators in the initializer of a global variable.
1651
1652 int
1653 Shortcuts::variable(Named_object* no)
1654 {
1655   if (no->is_result_variable())
1656     return TRAVERSE_CONTINUE;
1657   Variable* var = no->var_value();
1658   Expression* init = var->init();
1659   if (!var->is_global() || init == NULL)
1660     return TRAVERSE_CONTINUE;
1661
1662   while (true)
1663     {
1664       Find_shortcut find_shortcut;
1665       init->traverse(&init, &find_shortcut);
1666       Expression** pshortcut = find_shortcut.found();
1667       if (pshortcut == NULL)
1668         return TRAVERSE_CONTINUE;
1669
1670       Statement* snew = this->convert_shortcut(NULL, pshortcut);
1671       var->add_preinit_statement(snew);
1672       if (pshortcut == &init)
1673         var->set_init(init);
1674     }
1675 }
1676
1677 // Given an expression which uses a shortcut operator, return a
1678 // statement which implements it, and update *PSHORTCUT accordingly.
1679
1680 Statement*
1681 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1682 {
1683   Binary_expression* shortcut = (*pshortcut)->binary_expression();
1684   Expression* left = shortcut->left();
1685   Expression* right = shortcut->right();
1686   source_location loc = shortcut->location();
1687
1688   Block* retblock = new Block(enclosing, loc);
1689   retblock->set_end_location(loc);
1690
1691   Temporary_statement* ts = Statement::make_temporary(Type::make_boolean_type(),
1692                                                       left, loc);
1693   retblock->add_statement(ts);
1694
1695   Block* block = new Block(retblock, loc);
1696   block->set_end_location(loc);
1697   Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1698   Statement* assign = Statement::make_assignment(tmpref, right, loc);
1699   block->add_statement(assign);
1700
1701   Expression* cond = Expression::make_temporary_reference(ts, loc);
1702   if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1703     cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1704
1705   Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1706                                                          loc);
1707   retblock->add_statement(if_statement);
1708
1709   *pshortcut = Expression::make_temporary_reference(ts, loc);
1710
1711   delete shortcut;
1712
1713   // Now convert any shortcut operators in LEFT and RIGHT.
1714   Shortcuts shortcuts;
1715   retblock->traverse(&shortcuts);
1716
1717   return Statement::make_block_statement(retblock, loc);
1718 }
1719
1720 // Turn shortcut operators into explicit if statements.  Doing this
1721 // considerably simplifies the order of evaluation rules.
1722
1723 void
1724 Gogo::remove_shortcuts()
1725 {
1726   Shortcuts shortcuts;
1727   this->traverse(&shortcuts);
1728 }
1729
1730 // A traversal class which finds all the expressions which must be
1731 // evaluated in order within a statement or larger expression.  This
1732 // is used to implement the rules about order of evaluation.
1733
1734 class Find_eval_ordering : public Traverse
1735 {
1736  private:
1737   typedef std::vector<Expression**> Expression_pointers;
1738
1739  public:
1740   Find_eval_ordering()
1741     : Traverse(traverse_blocks
1742                | traverse_statements
1743                | traverse_expressions),
1744       exprs_()
1745   { }
1746
1747   size_t
1748   size() const
1749   { return this->exprs_.size(); }
1750
1751   typedef Expression_pointers::const_iterator const_iterator;
1752
1753   const_iterator
1754   begin() const
1755   { return this->exprs_.begin(); }
1756
1757   const_iterator
1758   end() const
1759   { return this->exprs_.end(); }
1760
1761  protected:
1762   int
1763   block(Block*)
1764   { return TRAVERSE_SKIP_COMPONENTS; }
1765
1766   int
1767   statement(Block*, size_t*, Statement*)
1768   { return TRAVERSE_SKIP_COMPONENTS; }
1769
1770   int
1771   expression(Expression**);
1772
1773  private:
1774   // A list of pointers to expressions with side-effects.
1775   Expression_pointers exprs_;
1776 };
1777
1778 // If an expression must be evaluated in order, put it on the list.
1779
1780 int
1781 Find_eval_ordering::expression(Expression** expression_pointer)
1782 {
1783   // We have to look at subexpressions before this one.
1784   if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1785     return TRAVERSE_EXIT;
1786   if ((*expression_pointer)->must_eval_in_order())
1787     this->exprs_.push_back(expression_pointer);
1788   return TRAVERSE_SKIP_COMPONENTS;
1789 }
1790
1791 // A traversal class for ordering evaluations.
1792
1793 class Order_eval : public Traverse
1794 {
1795  public:
1796   Order_eval()
1797     : Traverse(traverse_variables
1798                | traverse_statements)
1799   { }
1800
1801   int
1802   variable(Named_object*);
1803
1804   int
1805   statement(Block*, size_t*, Statement*);
1806 };
1807
1808 // Implement the order of evaluation rules for a statement.
1809
1810 int
1811 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1812 {
1813   // FIXME: This approach doesn't work for switch statements, because
1814   // we add the new statements before the whole switch when we need to
1815   // instead add them just before the switch expression.  The right
1816   // fix is probably to lower switch statements with nonconstant cases
1817   // to a series of conditionals.
1818   if (s->switch_statement() != NULL)
1819     return TRAVERSE_CONTINUE;
1820
1821   Find_eval_ordering find_eval_ordering;
1822
1823   // If S is a variable declaration, then ordinary traversal won't do
1824   // anything.  We want to explicitly traverse the initialization
1825   // expression if there is one.
1826   Variable_declaration_statement* vds = s->variable_declaration_statement();
1827   Expression* init = NULL;
1828   Expression* orig_init = NULL;
1829   if (vds == NULL)
1830     s->traverse_contents(&find_eval_ordering);
1831   else
1832     {
1833       init = vds->var()->var_value()->init();
1834       if (init == NULL)
1835         return TRAVERSE_CONTINUE;
1836       orig_init = init;
1837
1838       // It might seem that this could be
1839       // init->traverse_subexpressions.  Unfortunately that can fail
1840       // in a case like
1841       //   var err os.Error
1842       //   newvar, err := call(arg())
1843       // Here newvar will have an init of call result 0 of
1844       // call(arg()).  If we only traverse subexpressions, we will
1845       // only find arg(), and we won't bother to move anything out.
1846       // Then we get to the assignment to err, we will traverse the
1847       // whole statement, and this time we will find both call() and
1848       // arg(), and so we will move them out.  This will cause them to
1849       // be put into temporary variables before the assignment to err
1850       // but after the declaration of newvar.  To avoid that problem,
1851       // we traverse the entire expression here.
1852       Expression::traverse(&init, &find_eval_ordering);
1853     }
1854
1855   if (find_eval_ordering.size() <= 1)
1856     {
1857       // If there is only one expression with a side-effect, we can
1858       // leave it in place.
1859       return TRAVERSE_CONTINUE;
1860     }
1861
1862   bool is_thunk = s->thunk_statement() != NULL;
1863   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1864        p != find_eval_ordering.end();
1865        ++p)
1866     {
1867       Expression** pexpr = *p;
1868
1869       // If the last expression is a send or receive expression, we
1870       // may be ignoring the value; we don't want to evaluate it
1871       // early.
1872       if (p + 1 == find_eval_ordering.end()
1873           && ((*pexpr)->classification() == Expression::EXPRESSION_SEND
1874               || (*pexpr)->classification() == Expression::EXPRESSION_RECEIVE))
1875         break;
1876
1877       // The last expression in a thunk will be the call passed to go
1878       // or defer, which we must not evaluate early.
1879       if (is_thunk && p + 1 == find_eval_ordering.end())
1880         break;
1881
1882       source_location loc = (*pexpr)->location();
1883       Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1884       block->insert_statement_before(*pindex, ts);
1885       ++*pindex;
1886
1887       *pexpr = Expression::make_temporary_reference(ts, loc);
1888     }
1889
1890   if (init != orig_init)
1891     vds->var()->var_value()->set_init(init);
1892
1893   return TRAVERSE_CONTINUE;
1894 }
1895
1896 // Implement the order of evaluation rules for the initializer of a
1897 // global variable.
1898
1899 int
1900 Order_eval::variable(Named_object* no)
1901 {
1902   if (no->is_result_variable())
1903     return TRAVERSE_CONTINUE;
1904   Variable* var = no->var_value();
1905   Expression* init = var->init();
1906   if (!var->is_global() || init == NULL)
1907     return TRAVERSE_CONTINUE;
1908
1909   Find_eval_ordering find_eval_ordering;
1910   init->traverse_subexpressions(&find_eval_ordering);
1911
1912   if (find_eval_ordering.size() <= 1)
1913     {
1914       // If there is only one expression with a side-effect, we can
1915       // leave it in place.
1916       return TRAVERSE_SKIP_COMPONENTS;
1917     }
1918
1919   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1920        p != find_eval_ordering.end();
1921        ++p)
1922     {
1923       Expression** pexpr = *p;
1924       source_location loc = (*pexpr)->location();
1925       Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1926       var->add_preinit_statement(ts);
1927       *pexpr = Expression::make_temporary_reference(ts, loc);
1928     }
1929
1930   return TRAVERSE_SKIP_COMPONENTS;
1931 }
1932
1933 // Use temporary variables to implement the order of evaluation rules.
1934
1935 void
1936 Gogo::order_evaluations()
1937 {
1938   Order_eval order_eval;
1939   this->traverse(&order_eval);
1940 }
1941
1942 // Traversal to convert calls to the predeclared recover function to
1943 // pass in an argument indicating whether it can recover from a panic
1944 // or not.
1945
1946 class Convert_recover : public Traverse
1947 {
1948  public:
1949   Convert_recover(Named_object* arg)
1950     : Traverse(traverse_expressions),
1951       arg_(arg)
1952   { }
1953
1954  protected:
1955   int
1956   expression(Expression**);
1957
1958  private:
1959   // The argument to pass to the function.
1960   Named_object* arg_;
1961 };
1962
1963 // Convert calls to recover.
1964
1965 int
1966 Convert_recover::expression(Expression** pp)
1967 {
1968   Call_expression* ce = (*pp)->call_expression();
1969   if (ce != NULL && ce->is_recover_call())
1970     ce->set_recover_arg(Expression::make_var_reference(this->arg_,
1971                                                        ce->location()));
1972   return TRAVERSE_CONTINUE;
1973 }
1974
1975 // Traversal for build_recover_thunks.
1976
1977 class Build_recover_thunks : public Traverse
1978 {
1979  public:
1980   Build_recover_thunks(Gogo* gogo)
1981     : Traverse(traverse_functions),
1982       gogo_(gogo)
1983   { }
1984
1985   int
1986   function(Named_object*);
1987
1988  private:
1989   Expression*
1990   can_recover_arg(source_location);
1991
1992   // General IR.
1993   Gogo* gogo_;
1994 };
1995
1996 // If this function calls recover, turn it into a thunk.
1997
1998 int
1999 Build_recover_thunks::function(Named_object* orig_no)
2000 {
2001   Function* orig_func = orig_no->func_value();
2002   if (!orig_func->calls_recover()
2003       || orig_func->is_recover_thunk()
2004       || orig_func->has_recover_thunk())
2005     return TRAVERSE_CONTINUE;
2006
2007   Gogo* gogo = this->gogo_;
2008   source_location location = orig_func->location();
2009
2010   static int count;
2011   char buf[50];
2012
2013   Function_type* orig_fntype = orig_func->type();
2014   Typed_identifier_list* new_params = new Typed_identifier_list();
2015   std::string receiver_name;
2016   if (orig_fntype->is_method())
2017     {
2018       const Typed_identifier* receiver = orig_fntype->receiver();
2019       snprintf(buf, sizeof buf, "rt.%u", count);
2020       ++count;
2021       receiver_name = buf;
2022       new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2023                                              receiver->location()));
2024     }
2025   const Typed_identifier_list* orig_params = orig_fntype->parameters();
2026   if (orig_params != NULL && !orig_params->empty())
2027     {
2028       for (Typed_identifier_list::const_iterator p = orig_params->begin();
2029            p != orig_params->end();
2030            ++p)
2031         {
2032           snprintf(buf, sizeof buf, "pt.%u", count);
2033           ++count;
2034           new_params->push_back(Typed_identifier(buf, p->type(),
2035                                                  p->location()));
2036         }
2037     }
2038   snprintf(buf, sizeof buf, "pr.%u", count);
2039   ++count;
2040   std::string can_recover_name = buf;
2041   new_params->push_back(Typed_identifier(can_recover_name,
2042                                          Type::make_boolean_type(),
2043                                          orig_fntype->location()));
2044
2045   const Typed_identifier_list* orig_results = orig_fntype->results();
2046   Typed_identifier_list* new_results;
2047   if (orig_results == NULL || orig_results->empty())
2048     new_results = NULL;
2049   else
2050     {
2051       new_results = new Typed_identifier_list();
2052       for (Typed_identifier_list::const_iterator p = orig_results->begin();
2053            p != orig_results->end();
2054            ++p)
2055         new_results->push_back(*p);
2056     }
2057
2058   Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2059                                                        new_results,
2060                                                        orig_fntype->location());
2061   if (orig_fntype->is_varargs())
2062     new_fntype->set_is_varargs();
2063
2064   std::string name = orig_no->name() + "$recover";
2065   Named_object *new_no = gogo->start_function(name, new_fntype, false,
2066                                               location);
2067   Function *new_func = new_no->func_value();
2068   if (orig_func->enclosing() != NULL)
2069     new_func->set_enclosing(orig_func->enclosing());
2070
2071   // We build the code for the original function attached to the new
2072   // function, and then swap the original and new function bodies.
2073   // This means that existing references to the original function will
2074   // then refer to the new function.  That makes this code a little
2075   // confusing, in that the reference to NEW_NO really refers to the
2076   // other function, not the one we are building.
2077
2078   Expression* closure = NULL;
2079   if (orig_func->needs_closure())
2080     {
2081       Named_object* orig_closure_no = orig_func->closure_var();
2082       Variable* orig_closure_var = orig_closure_no->var_value();
2083       Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2084                                        true, false, location);
2085       snprintf(buf, sizeof buf, "closure.%u", count);
2086       ++count;
2087       Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2088                                                                  new_var);
2089       new_func->set_closure_var(new_closure_no);
2090       closure = Expression::make_var_reference(new_closure_no, location);
2091     }
2092
2093   Expression* fn = Expression::make_func_reference(new_no, closure, location);
2094
2095   Expression_list* args = new Expression_list();
2096   if (orig_fntype->is_method())
2097     {
2098       Named_object* rec_no = gogo->lookup(receiver_name, NULL);
2099       gcc_assert(rec_no != NULL
2100                  && rec_no->is_variable()
2101                  && rec_no->var_value()->is_parameter());
2102       args->push_back(Expression::make_var_reference(rec_no, location));
2103     }
2104   if (new_params != NULL)
2105     {
2106       // Note that we skip the last parameter, which is the boolean
2107       // indicating whether recover can succed.
2108       for (Typed_identifier_list::const_iterator p = new_params->begin();
2109            p + 1 != new_params->end();
2110            ++p)
2111         {
2112           Named_object* p_no = gogo->lookup(p->name(), NULL);
2113           gcc_assert(p_no != NULL
2114                      && p_no->is_variable()
2115                      && p_no->var_value()->is_parameter());
2116           args->push_back(Expression::make_var_reference(p_no, location));
2117         }
2118     }
2119   args->push_back(this->can_recover_arg(location));
2120
2121   Expression* call = Expression::make_call(fn, args, false, location);
2122
2123   Statement* s;
2124   if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2125     s = Statement::make_statement(call);
2126   else
2127     {
2128       Expression_list* vals = new Expression_list();
2129       vals->push_back(call);
2130       s = Statement::make_return_statement(new_func->type()->results(),
2131                                            vals, location);
2132     }
2133   s->determine_types();
2134   gogo->add_statement(s);
2135
2136   gogo->finish_function(location);
2137
2138   // Swap the function bodies and types.
2139   new_func->swap_for_recover(orig_func);
2140   orig_func->set_is_recover_thunk();
2141   new_func->set_calls_recover();
2142   new_func->set_has_recover_thunk();
2143
2144   Bindings* orig_bindings = orig_func->block()->bindings();
2145   Bindings* new_bindings = new_func->block()->bindings();
2146   if (orig_fntype->is_method())
2147     {
2148       // We changed the receiver to be a regular parameter.  We have
2149       // to update the binding accordingly in both functions.
2150       Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2151       gcc_assert(orig_rec_no != NULL
2152                  && orig_rec_no->is_variable()
2153                  && !orig_rec_no->var_value()->is_receiver());
2154       orig_rec_no->var_value()->set_is_receiver();
2155
2156       Named_object* new_rec_no = new_bindings->lookup_local(receiver_name);
2157       gcc_assert(new_rec_no != NULL
2158                  && new_rec_no->is_variable()
2159                  && !new_rec_no->var_value()->is_receiver());
2160       new_rec_no->var_value()->set_is_not_receiver();
2161     }
2162
2163   // Because we flipped blocks but not types, the can_recover
2164   // parameter appears in the (now) old bindings as a parameter.
2165   // Change it to a local variable, whereupon it will be discarded.
2166   Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2167   gcc_assert(can_recover_no != NULL
2168              && can_recover_no->is_variable()
2169              && can_recover_no->var_value()->is_parameter());
2170   orig_bindings->remove_binding(can_recover_no);
2171
2172   // Add the can_recover argument to the (now) new bindings, and
2173   // attach it to any recover statements.
2174   Variable* can_recover_var = new Variable(Type::make_boolean_type(), NULL,
2175                                            false, true, false, location);
2176   can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2177                                               can_recover_var);
2178   Convert_recover convert_recover(can_recover_no);
2179   new_func->traverse(&convert_recover);
2180
2181   return TRAVERSE_CONTINUE;
2182 }
2183
2184 // Return the expression to pass for the .can_recover parameter to the
2185 // new function.  This indicates whether a call to recover may return
2186 // non-nil.  The expression is
2187 // __go_can_recover(__builtin_return_address()).
2188
2189 Expression*
2190 Build_recover_thunks::can_recover_arg(source_location location)
2191 {
2192   static Named_object* builtin_return_address;
2193   if (builtin_return_address == NULL)
2194     {
2195       const source_location bloc = BUILTINS_LOCATION;
2196
2197       Typed_identifier_list* param_types = new Typed_identifier_list();
2198       Type* uint_type = Type::lookup_integer_type("uint");
2199       param_types->push_back(Typed_identifier("l", uint_type, bloc));
2200
2201       Typed_identifier_list* return_types = new Typed_identifier_list();
2202       Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2203       return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2204
2205       Function_type* fntype = Type::make_function_type(NULL, param_types,
2206                                                        return_types, bloc);
2207       builtin_return_address =
2208         Named_object::make_function_declaration("__builtin_return_address",
2209                                                 NULL, fntype, bloc);
2210       const char* n = "__builtin_return_address";
2211       builtin_return_address->func_declaration_value()->set_asm_name(n);
2212     }
2213
2214   static Named_object* can_recover;
2215   if (can_recover == NULL)
2216     {
2217       const source_location bloc = BUILTINS_LOCATION;
2218       Typed_identifier_list* param_types = new Typed_identifier_list();
2219       Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2220       param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2221       Type* boolean_type = Type::make_boolean_type();
2222       Typed_identifier_list* results = new Typed_identifier_list();
2223       results->push_back(Typed_identifier("", boolean_type, bloc));
2224       Function_type* fntype = Type::make_function_type(NULL, param_types,
2225                                                        results, bloc);
2226       can_recover = Named_object::make_function_declaration("__go_can_recover",
2227                                                             NULL, fntype,
2228                                                             bloc);
2229       can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2230     }
2231
2232   Expression* fn = Expression::make_func_reference(builtin_return_address,
2233                                                    NULL, location);
2234
2235   mpz_t zval;
2236   mpz_init_set_ui(zval, 0UL);
2237   Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2238   mpz_clear(zval);
2239   Expression_list *args = new Expression_list();
2240   args->push_back(zexpr);
2241
2242   Expression* call = Expression::make_call(fn, args, false, location);
2243
2244   args = new Expression_list();
2245   args->push_back(call);
2246
2247   fn = Expression::make_func_reference(can_recover, NULL, location);
2248   return Expression::make_call(fn, args, false, location);
2249 }
2250
2251 // Build thunks for functions which call recover.  We build a new
2252 // function with an extra parameter, which is whether a call to
2253 // recover can succeed.  We then move the body of this function to
2254 // that one.  We then turn this function into a thunk which calls the
2255 // new one, passing the value of
2256 // __go_can_recover(__builtin_return_address()).  The function will be
2257 // marked as not splitting the stack.  This will cooperate with the
2258 // implementation of defer to make recover do the right thing.
2259
2260 void
2261 Gogo::build_recover_thunks()
2262 {
2263   Build_recover_thunks build_recover_thunks(this);
2264   this->traverse(&build_recover_thunks);
2265 }
2266
2267 // Look for named types to see whether we need to create an interface
2268 // method table.
2269
2270 class Build_method_tables : public Traverse
2271 {
2272  public:
2273   Build_method_tables(Gogo* gogo,
2274                       const std::vector<Interface_type*>& interfaces)
2275     : Traverse(traverse_types),
2276       gogo_(gogo), interfaces_(interfaces)
2277   { }
2278
2279   int
2280   type(Type*);
2281
2282  private:
2283   // The IR.
2284   Gogo* gogo_;
2285   // A list of locally defined interfaces which have hidden methods.
2286   const std::vector<Interface_type*>& interfaces_;
2287 };
2288
2289 // Build all required interface method tables for types.  We need to
2290 // ensure that we have an interface method table for every interface
2291 // which has a hidden method, for every named type which implements
2292 // that interface.  Normally we can just build interface method tables
2293 // as we need them.  However, in some cases we can require an
2294 // interface method table for an interface defined in a different
2295 // package for a type defined in that package.  If that interface and
2296 // type both use a hidden method, that is OK.  However, we will not be
2297 // able to build that interface method table when we need it, because
2298 // the type's hidden method will be static.  So we have to build it
2299 // here, and just refer it from other packages as needed.
2300
2301 void
2302 Gogo::build_interface_method_tables()
2303 {
2304   std::vector<Interface_type*> hidden_interfaces;
2305   hidden_interfaces.reserve(this->interface_types_.size());
2306   for (std::vector<Interface_type*>::const_iterator pi =
2307          this->interface_types_.begin();
2308        pi != this->interface_types_.end();
2309        ++pi)
2310     {
2311       const Typed_identifier_list* methods = (*pi)->methods();
2312       if (methods == NULL)
2313         continue;
2314       for (Typed_identifier_list::const_iterator pm = methods->begin();
2315            pm != methods->end();
2316            ++pm)
2317         {
2318           if (Gogo::is_hidden_name(pm->name()))
2319             {
2320               hidden_interfaces.push_back(*pi);
2321               break;
2322             }
2323         }
2324     }
2325
2326   if (!hidden_interfaces.empty())
2327     {
2328       // Now traverse the tree looking for all named types.
2329       Build_method_tables bmt(this, hidden_interfaces);
2330       this->traverse(&bmt);
2331     }
2332
2333   // We no longer need the list of interfaces.
2334
2335   this->interface_types_.clear();
2336 }
2337
2338 // This is called for each type.  For a named type, for each of the
2339 // interfaces with hidden methods that it implements, create the
2340 // method table.
2341
2342 int
2343 Build_method_tables::type(Type* type)
2344 {
2345   Named_type* nt = type->named_type();
2346   if (nt != NULL)
2347     {
2348       for (std::vector<Interface_type*>::const_iterator p =
2349              this->interfaces_.begin();
2350            p != this->interfaces_.end();
2351            ++p)
2352         {
2353           // We ask whether a pointer to the named type implements the
2354           // interface, because a pointer can implement more methods
2355           // than a value.
2356           if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2357             {
2358               nt->interface_method_table(this->gogo_, *p, false);
2359               nt->interface_method_table(this->gogo_, *p, true);
2360             }
2361         }
2362     }
2363   return TRAVERSE_CONTINUE;
2364 }
2365
2366 // Traversal class used to check for return statements.
2367
2368 class Check_return_statements_traverse : public Traverse
2369 {
2370  public:
2371   Check_return_statements_traverse()
2372     : Traverse(traverse_functions)
2373   { }
2374
2375   int
2376   function(Named_object*);
2377 };
2378
2379 // Check that a function has a return statement if it needs one.
2380
2381 int
2382 Check_return_statements_traverse::function(Named_object* no)
2383 {
2384   Function* func = no->func_value();
2385   const Function_type* fntype = func->type();
2386   const Typed_identifier_list* results = fntype->results();
2387
2388   // We only need a return statement if there is a return value.
2389   if (results == NULL || results->empty())
2390     return TRAVERSE_CONTINUE;
2391
2392   if (func->block()->may_fall_through())
2393     error_at(func->location(), "control reaches end of non-void function");
2394
2395   return TRAVERSE_CONTINUE;
2396 }
2397
2398 // Check return statements.
2399
2400 void
2401 Gogo::check_return_statements()
2402 {
2403   Check_return_statements_traverse traverse;
2404   this->traverse(&traverse);
2405 }
2406
2407 // Get the unique prefix to use before all exported symbols.  This
2408 // must be unique across the entire link.
2409
2410 const std::string&
2411 Gogo::unique_prefix() const
2412 {
2413   gcc_assert(!this->unique_prefix_.empty());
2414   return this->unique_prefix_;
2415 }
2416
2417 // Set the unique prefix to use before all exported symbols.  This
2418 // comes from the command line option -fgo-prefix=XXX.
2419
2420 void
2421 Gogo::set_unique_prefix(const std::string& arg)
2422 {
2423   gcc_assert(this->unique_prefix_.empty());
2424   this->unique_prefix_ = arg;
2425 }
2426
2427 // Work out the package priority.  It is one more than the maximum
2428 // priority of an imported package.
2429
2430 int
2431 Gogo::package_priority() const
2432 {
2433   int priority = 0;
2434   for (Packages::const_iterator p = this->packages_.begin();
2435        p != this->packages_.end();
2436        ++p)
2437     if (p->second->priority() > priority)
2438       priority = p->second->priority();
2439   return priority + 1;
2440 }
2441
2442 // Export identifiers as requested.
2443
2444 void
2445 Gogo::do_exports()
2446 {
2447   // For now we always stream to a section.  Later we may want to
2448   // support streaming to a separate file.
2449   Stream_to_section stream;
2450
2451   Export exp(&stream);
2452   exp.register_builtin_types(this);
2453   exp.export_globals(this->package_name(),
2454                      this->unique_prefix(),
2455                      this->package_priority(),
2456                      (this->need_init_fn_ && this->package_name() != "main"
2457                       ? this->get_init_fn_name()
2458                       : ""),
2459                      this->imported_init_fns_,
2460                      this->package_->bindings());
2461 }
2462
2463 // Class Function.
2464
2465 Function::Function(Function_type* type, Function* enclosing, Block* block,
2466                    source_location location)
2467   : type_(type), enclosing_(enclosing), named_results_(NULL),
2468     closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2469     defer_stack_(NULL), calls_recover_(false), is_recover_thunk_(false),
2470     has_recover_thunk_(false)
2471 {
2472 }
2473
2474 // Create the named result variables.
2475
2476 void
2477 Function::create_named_result_variables(Gogo* gogo)
2478 {
2479   const Typed_identifier_list* results = this->type_->results();
2480   if (results == NULL
2481       || results->empty()
2482       || results->front().name().empty())
2483     return;
2484
2485   this->named_results_ = new Named_results();
2486   this->named_results_->reserve(results->size());
2487
2488   Block* block = this->block_;
2489   int index = 0;
2490   for (Typed_identifier_list::const_iterator p = results->begin();
2491        p != results->end();
2492        ++p, ++index)
2493     {
2494       std::string name = p->name();
2495       if (Gogo::is_sink_name(name))
2496         {
2497           static int unnamed_result_counter;
2498           char buf[100];
2499           snprintf(buf, sizeof buf, "_$%d", unnamed_result_counter);
2500           ++unnamed_result_counter;
2501           name = gogo->pack_hidden_name(buf, false);
2502         }
2503       Result_variable* result = new Result_variable(p->type(), this, index);
2504       Named_object* no = block->bindings()->add_result_variable(name, result);
2505       this->named_results_->push_back(no);
2506     }
2507 }
2508
2509 // Return the closure variable, creating it if necessary.
2510
2511 Named_object*
2512 Function::closure_var()
2513 {
2514   if (this->closure_var_ == NULL)
2515     {
2516       // We don't know the type of the variable yet.  We add fields as
2517       // we find them.
2518       source_location loc = this->type_->location();
2519       Struct_field_list* sfl = new Struct_field_list;
2520       Type* struct_type = Type::make_struct_type(sfl, loc);
2521       Variable* var = new Variable(Type::make_pointer_type(struct_type),
2522                                    NULL, false, true, false, loc);
2523       this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2524       // Note that the new variable is not in any binding contour.
2525     }
2526   return this->closure_var_;
2527 }
2528
2529 // Set the type of the closure variable.
2530
2531 void
2532 Function::set_closure_type()
2533 {
2534   if (this->closure_var_ == NULL)
2535     return;
2536   Named_object* closure = this->closure_var_;
2537   Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2538   unsigned int index = 0;
2539   for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2540        p != this->closure_fields_.end();
2541        ++p, ++index)
2542     {
2543       Named_object* no = p->first;
2544       char buf[20];
2545       snprintf(buf, sizeof buf, "%u", index);
2546       std::string n = no->name() + buf;
2547       Type* var_type;
2548       if (no->is_variable())
2549         var_type = no->var_value()->type();
2550       else
2551         var_type = no->result_var_value()->type();
2552       Type* field_type = Type::make_pointer_type(var_type);
2553       st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2554     }
2555 }
2556
2557 // Return whether this function is a method.
2558
2559 bool
2560 Function::is_method() const
2561 {
2562   return this->type_->is_method();
2563 }
2564
2565 // Add a label definition.
2566
2567 Label*
2568 Function::add_label_definition(const std::string& label_name,
2569                                source_location location)
2570 {
2571   Label* lnull = NULL;
2572   std::pair<Labels::iterator, bool> ins =
2573     this->labels_.insert(std::make_pair(label_name, lnull));
2574   if (ins.second)
2575     {
2576       // This is a new label.
2577       Label* label = new Label(label_name);
2578       label->define(location);
2579       ins.first->second = label;
2580       return label;
2581     }
2582   else
2583     {
2584       // The label was already in the hash table.
2585       Label* label = ins.first->second;
2586       if (!label->is_defined())
2587         {
2588           label->define(location);
2589           return label;
2590         }
2591       else
2592         {
2593           error_at(location, "redefinition of label %qs",
2594                    Gogo::message_name(label_name).c_str());
2595           inform(label->location(), "previous definition of %qs was here",
2596                  Gogo::message_name(label_name).c_str());
2597           return new Label(label_name);
2598         }
2599     }
2600 }
2601
2602 // Add a reference to a label.
2603
2604 Label*
2605 Function::add_label_reference(const std::string& label_name)
2606 {
2607   Label* lnull = NULL;
2608   std::pair<Labels::iterator, bool> ins =
2609     this->labels_.insert(std::make_pair(label_name, lnull));
2610   if (!ins.second)
2611     {
2612       // The label was already in the hash table.
2613       return ins.first->second;
2614     }
2615   else
2616     {
2617       gcc_assert(ins.first->second == NULL);
2618       Label* label = new Label(label_name);
2619       ins.first->second = label;
2620       return label;
2621     }
2622 }
2623
2624 // Swap one function with another.  This is used when building the
2625 // thunk we use to call a function which calls recover.  It may not
2626 // work for any other case.
2627
2628 void
2629 Function::swap_for_recover(Function *x)
2630 {
2631   gcc_assert(this->enclosing_ == x->enclosing_);
2632   gcc_assert(this->named_results_ == x->named_results_);
2633   std::swap(this->closure_var_, x->closure_var_);
2634   std::swap(this->block_, x->block_);
2635   gcc_assert(this->location_ == x->location_);
2636   gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2637   gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2638 }
2639
2640 // Traverse the tree.
2641
2642 int
2643 Function::traverse(Traverse* traverse)
2644 {
2645   unsigned int traverse_mask = traverse->traverse_mask();
2646
2647   if ((traverse_mask
2648        & (Traverse::traverse_types | Traverse::traverse_expressions))
2649       != 0)
2650     {
2651       if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2652         return TRAVERSE_EXIT;
2653     }
2654
2655   // FIXME: We should check traverse_functions here if nested
2656   // functions are stored in block bindings.
2657   if (this->block_ != NULL
2658       && (traverse_mask
2659           & (Traverse::traverse_variables
2660              | Traverse::traverse_constants
2661              | Traverse::traverse_blocks
2662              | Traverse::traverse_statements
2663              | Traverse::traverse_expressions
2664              | Traverse::traverse_types)) != 0)
2665     {
2666       if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2667         return TRAVERSE_EXIT;
2668     }
2669
2670   return TRAVERSE_CONTINUE;
2671 }
2672
2673 // Work out types for unspecified variables and constants.
2674
2675 void
2676 Function::determine_types()
2677 {
2678   if (this->block_ != NULL)
2679     this->block_->determine_types();
2680 }
2681
2682 // Export the function.
2683
2684 void
2685 Function::export_func(Export* exp, const std::string& name) const
2686 {
2687   Function::export_func_with_type(exp, name, this->type_);
2688 }
2689
2690 // Export a function with a type.
2691
2692 void
2693 Function::export_func_with_type(Export* exp, const std::string& name,
2694                                 const Function_type* fntype)
2695 {
2696   exp->write_c_string("func ");
2697
2698   if (fntype->is_method())
2699     {
2700       exp->write_c_string("(");
2701       exp->write_type(fntype->receiver()->type());
2702       exp->write_c_string(") ");
2703     }
2704
2705   exp->write_string(name);
2706
2707   exp->write_c_string(" (");
2708   const Typed_identifier_list* parameters = fntype->parameters();
2709   if (parameters != NULL)
2710     {
2711       bool is_varargs = fntype->is_varargs();
2712       bool first = true;
2713       for (Typed_identifier_list::const_iterator p = parameters->begin();
2714            p != parameters->end();
2715            ++p)
2716         {
2717           if (first)
2718             first = false;
2719           else
2720             exp->write_c_string(", ");
2721           if (!is_varargs || p + 1 != parameters->end())
2722             exp->write_type(p->type());
2723           else
2724             {
2725               exp->write_c_string("...");
2726               exp->write_type(p->type()->array_type()->element_type());
2727             }
2728         }
2729     }
2730   exp->write_c_string(")");
2731
2732   const Typed_identifier_list* results = fntype->results();
2733   if (results != NULL)
2734     {
2735       if (results->size() == 1)
2736         {
2737           exp->write_c_string(" ");
2738           exp->write_type(results->begin()->type());
2739         }
2740       else
2741         {
2742           exp->write_c_string(" (");
2743           bool first = true;
2744           for (Typed_identifier_list::const_iterator p = results->begin();
2745                p != results->end();
2746                ++p)
2747             {
2748               if (first)
2749                 first = false;
2750               else
2751                 exp->write_c_string(", ");
2752               exp->write_type(p->type());
2753             }
2754           exp->write_c_string(")");
2755         }
2756     }
2757   exp->write_c_string(";\n");
2758 }
2759
2760 // Import a function.
2761
2762 void
2763 Function::import_func(Import* imp, std::string* pname,
2764                       Typed_identifier** preceiver,
2765                       Typed_identifier_list** pparameters,
2766                       Typed_identifier_list** presults,
2767                       bool* is_varargs)
2768 {
2769   imp->require_c_string("func ");
2770
2771   *preceiver = NULL;
2772   if (imp->peek_char() == '(')
2773     {
2774       imp->require_c_string("(");
2775       Type* rtype = imp->read_type();
2776       *preceiver = new Typed_identifier(Import::import_marker, rtype,
2777                                         imp->location());
2778       imp->require_c_string(") ");
2779     }
2780
2781   *pname = imp->read_identifier();
2782
2783   Typed_identifier_list* parameters;
2784   *is_varargs = false;
2785   imp->require_c_string(" (");
2786   if (imp->peek_char() == ')')
2787     parameters = NULL;
2788   else
2789     {
2790       parameters = new Typed_identifier_list();
2791       while (true)
2792         {
2793           if (imp->match_c_string("..."))
2794             {
2795               imp->advance(3);
2796               *is_varargs = true;
2797             }
2798
2799           Type* ptype = imp->read_type();
2800           if (*is_varargs)
2801             ptype = Type::make_array_type(ptype, NULL);
2802           parameters->push_back(Typed_identifier(Import::import_marker,
2803                                                  ptype, imp->location()));
2804           if (imp->peek_char() != ',')
2805             break;
2806           gcc_assert(!*is_varargs);
2807           imp->require_c_string(", ");
2808         }
2809     }
2810   imp->require_c_string(")");
2811   *pparameters = parameters;
2812
2813   Typed_identifier_list* results;
2814   if (imp->peek_char() != ' ')
2815     results = NULL;
2816   else
2817     {
2818       results = new Typed_identifier_list();
2819       imp->require_c_string(" ");
2820       if (imp->peek_char() != '(')
2821         {
2822           Type* rtype = imp->read_type();
2823           results->push_back(Typed_identifier(Import::import_marker, rtype,
2824                                               imp->location()));
2825         }
2826       else
2827         {
2828           imp->require_c_string("(");
2829           while (true)
2830             {
2831               Type* rtype = imp->read_type();
2832               results->push_back(Typed_identifier(Import::import_marker,
2833                                                   rtype, imp->location()));
2834               if (imp->peek_char() != ',')
2835                 break;
2836               imp->require_c_string(", ");
2837             }
2838           imp->require_c_string(")");
2839         }
2840     }
2841   imp->require_c_string(";\n");
2842   *presults = results;
2843 }
2844
2845 // Class Block.
2846
2847 Block::Block(Block* enclosing, source_location location)
2848   : enclosing_(enclosing), statements_(),
2849     bindings_(new Bindings(enclosing == NULL
2850                            ? NULL
2851                            : enclosing->bindings())),
2852     start_location_(location),
2853     end_location_(UNKNOWN_LOCATION)
2854 {
2855 }
2856
2857 // Add a statement to a block.
2858
2859 void
2860 Block::add_statement(Statement* statement)
2861 {
2862   this->statements_.push_back(statement);
2863 }
2864
2865 // Add a statement to the front of a block.  This is slow but is only
2866 // used for reference counts of parameters.
2867
2868 void
2869 Block::add_statement_at_front(Statement* statement)
2870 {
2871   this->statements_.insert(this->statements_.begin(), statement);
2872 }
2873
2874 // Replace a statement in a block.
2875
2876 void
2877 Block::replace_statement(size_t index, Statement* s)
2878 {
2879   gcc_assert(index < this->statements_.size());
2880   this->statements_[index] = s;
2881 }
2882
2883 // Add a statement before another statement.
2884
2885 void
2886 Block::insert_statement_before(size_t index, Statement* s)
2887 {
2888   gcc_assert(index < this->statements_.size());
2889   this->statements_.insert(this->statements_.begin() + index, s);
2890 }
2891
2892 // Add a statement after another statement.
2893
2894 void
2895 Block::insert_statement_after(size_t index, Statement* s)
2896 {
2897   gcc_assert(index < this->statements_.size());
2898   this->statements_.insert(this->statements_.begin() + index + 1, s);
2899 }
2900
2901 // Traverse the tree.
2902
2903 int
2904 Block::traverse(Traverse* traverse)
2905 {
2906   unsigned int traverse_mask = traverse->traverse_mask();
2907
2908   if ((traverse_mask & Traverse::traverse_blocks) != 0)
2909     {
2910       int t = traverse->block(this);
2911       if (t == TRAVERSE_EXIT)
2912         return TRAVERSE_EXIT;
2913       else if (t == TRAVERSE_SKIP_COMPONENTS)
2914         return TRAVERSE_CONTINUE;
2915     }
2916
2917   if ((traverse_mask
2918        & (Traverse::traverse_variables
2919           | Traverse::traverse_constants
2920           | Traverse::traverse_expressions
2921           | Traverse::traverse_types)) != 0)
2922     {
2923       for (Bindings::const_definitions_iterator pb =
2924              this->bindings_->begin_definitions();
2925            pb != this->bindings_->end_definitions();
2926            ++pb)
2927         {
2928           switch ((*pb)->classification())
2929             {
2930             case Named_object::NAMED_OBJECT_CONST:
2931               if ((traverse_mask & Traverse::traverse_constants) != 0)
2932                 {
2933                   if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
2934                     return TRAVERSE_EXIT;
2935                 }
2936               if ((traverse_mask & Traverse::traverse_types) != 0
2937                   || (traverse_mask & Traverse::traverse_expressions) != 0)
2938                 {
2939                   Type* t = (*pb)->const_value()->type();
2940                   if (t != NULL
2941                       && Type::traverse(t, traverse) == TRAVERSE_EXIT)
2942                     return TRAVERSE_EXIT;
2943                 }
2944               if ((traverse_mask & Traverse::traverse_expressions) != 0
2945                   || (traverse_mask & Traverse::traverse_types) != 0)
2946                 {
2947                   if ((*pb)->const_value()->traverse_expression(traverse)
2948                       == TRAVERSE_EXIT)
2949                     return TRAVERSE_EXIT;
2950                 }
2951               break;
2952
2953             case Named_object::NAMED_OBJECT_VAR:
2954             case Named_object::NAMED_OBJECT_RESULT_VAR:
2955               if ((traverse_mask & Traverse::traverse_variables) != 0)
2956                 {
2957                   if (traverse->variable(*pb) == TRAVERSE_EXIT)
2958                     return TRAVERSE_EXIT;
2959                 }
2960               if (((traverse_mask & Traverse::traverse_types) != 0
2961                    || (traverse_mask & Traverse::traverse_expressions) != 0)
2962                   && ((*pb)->is_result_variable()
2963                       || (*pb)->var_value()->has_type()))
2964                 {
2965                   Type* t = ((*pb)->is_variable()
2966                              ? (*pb)->var_value()->type()
2967                              : (*pb)->result_var_value()->type());
2968                   if (t != NULL
2969                       && Type::traverse(t, traverse) == TRAVERSE_EXIT)
2970                     return TRAVERSE_EXIT;
2971                 }
2972               if ((*pb)->is_variable()
2973                   && ((traverse_mask & Traverse::traverse_expressions) != 0
2974                       || (traverse_mask & Traverse::traverse_types) != 0))
2975                 {
2976                   if ((*pb)->var_value()->traverse_expression(traverse)
2977                       == TRAVERSE_EXIT)
2978                     return TRAVERSE_EXIT;
2979                 }
2980               break;
2981
2982             case Named_object::NAMED_OBJECT_FUNC:
2983             case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2984               // FIXME: Where will nested functions be found?
2985               gcc_unreachable();
2986
2987             case Named_object::NAMED_OBJECT_TYPE:
2988               if ((traverse_mask & Traverse::traverse_types) != 0
2989                   || (traverse_mask & Traverse::traverse_expressions) != 0)
2990                 {
2991                   if (Type::traverse((*pb)->type_value(), traverse)
2992                       == TRAVERSE_EXIT)
2993                     return TRAVERSE_EXIT;
2994                 }
2995               break;
2996
2997             case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2998             case Named_object::NAMED_OBJECT_UNKNOWN:
2999               break;
3000
3001             case Named_object::NAMED_OBJECT_PACKAGE:
3002             case Named_object::NAMED_OBJECT_SINK:
3003               gcc_unreachable();
3004
3005             default:
3006               gcc_unreachable();
3007             }
3008         }
3009     }
3010
3011   // No point in checking traverse_mask here--if we got here we always
3012   // want to walk the statements.  The traversal can insert new
3013   // statements before or after the current statement.  Inserting
3014   // statements before the current statement requires updating I via
3015   // the pointer; those statements will not be traversed.  Any new
3016   // statements inserted after the current statement will be traversed
3017   // in their turn.
3018   for (size_t i = 0; i < this->statements_.size(); ++i)
3019     {
3020       if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3021         return TRAVERSE_EXIT;
3022     }
3023
3024   return TRAVERSE_CONTINUE;
3025 }
3026
3027 // Work out types for unspecified variables and constants.
3028
3029 void
3030 Block::determine_types()
3031 {
3032   for (Bindings::const_definitions_iterator pb =
3033          this->bindings_->begin_definitions();
3034        pb != this->bindings_->end_definitions();
3035        ++pb)
3036     {
3037       if ((*pb)->is_variable())
3038         (*pb)->var_value()->determine_type();
3039       else if ((*pb)->is_const())
3040         (*pb)->const_value()->determine_type();
3041     }
3042
3043   for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3044        ps != this->statements_.end();
3045        ++ps)
3046     (*ps)->determine_types();
3047 }
3048
3049 // Return true if the statements in this block may fall through.
3050
3051 bool
3052 Block::may_fall_through() const
3053 {
3054   if (this->statements_.empty())
3055     return true;
3056   return this->statements_.back()->may_fall_through();
3057 }
3058
3059 // Class Variable.
3060
3061 Variable::Variable(Type* type, Expression* init, bool is_global,
3062                    bool is_parameter, bool is_receiver,
3063                    source_location location)
3064   : type_(type), init_(init), preinit_(NULL), location_(location),
3065     is_global_(is_global), is_parameter_(is_parameter),
3066     is_receiver_(is_receiver), is_varargs_parameter_(false),
3067     is_address_taken_(false), seen_(false), init_is_lowered_(false),
3068     type_from_init_tuple_(false), type_from_range_index_(false),
3069     type_from_range_value_(false), type_from_chan_element_(false),
3070     is_type_switch_var_(false)
3071 {
3072   gcc_assert(type != NULL || init != NULL);
3073   gcc_assert(!is_parameter || init == NULL);
3074 }
3075
3076 // Traverse the initializer expression.
3077
3078 int
3079 Variable::traverse_expression(Traverse* traverse)
3080 {
3081   if (this->preinit_ != NULL)
3082     {
3083       if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3084         return TRAVERSE_EXIT;
3085     }
3086   if (this->init_ != NULL)
3087     {
3088       if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3089         return TRAVERSE_EXIT;
3090     }
3091   return TRAVERSE_CONTINUE;
3092 }
3093
3094 // Lower the initialization expression after parsing is complete.
3095
3096 void
3097 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3098 {
3099   if (this->init_ != NULL && !this->init_is_lowered_)
3100     {
3101       if (this->seen_)
3102         {
3103           // We will give an error elsewhere, this is just to prevent
3104           // an infinite loop.
3105           return;
3106         }
3107       this->seen_ = true;
3108
3109       gogo->lower_expression(function, &this->init_);
3110
3111       this->seen_ = false;
3112
3113       this->init_is_lowered_ = true;
3114     }
3115 }
3116
3117 // Get the preinit block.
3118
3119 Block*
3120 Variable::preinit_block()
3121 {
3122   gcc_assert(this->is_global_);
3123   if (this->preinit_ == NULL)
3124     this->preinit_ = new Block(NULL, this->location());
3125   return this->preinit_;
3126 }
3127
3128 // Add a statement to be run before the initialization expression.
3129
3130 void
3131 Variable::add_preinit_statement(Statement* s)
3132 {
3133   Block* b = this->preinit_block();
3134   b->add_statement(s);
3135   b->set_end_location(s->location());
3136 }
3137
3138 // In an assignment which sets a variable to a tuple of EXPR, return
3139 // the type of the first element of the tuple.
3140
3141 Type*
3142 Variable::type_from_tuple(Expression* expr, bool report_error) const
3143 {
3144   if (expr->map_index_expression() != NULL)
3145     return expr->map_index_expression()->get_map_type()->val_type();
3146   else if (expr->receive_expression() != NULL)
3147     {
3148       Expression* channel = expr->receive_expression()->channel();
3149       Type* channel_type = channel->type();
3150       if (channel_type->is_error_type())
3151         return Type::make_error_type();
3152       return channel_type->channel_type()->element_type();
3153     }
3154   else
3155     {
3156       if (report_error)
3157         error_at(this->location(), "invalid tuple definition");
3158       return Type::make_error_type();
3159     }
3160 }
3161
3162 // Given EXPR used in a range clause, return either the index type or
3163 // the value type of the range, depending upon GET_INDEX_TYPE.
3164
3165 Type*
3166 Variable::type_from_range(Expression* expr, bool get_index_type,
3167                           bool report_error) const
3168 {
3169   Type* t = expr->type();
3170   if (t->array_type() != NULL
3171       || (t->points_to() != NULL
3172           && t->points_to()->array_type() != NULL
3173           && !t->points_to()->is_open_array_type()))
3174     {
3175       if (get_index_type)
3176         return Type::lookup_integer_type("int");
3177       else
3178         return t->deref()->array_type()->element_type();
3179     }
3180   else if (t->is_string_type())
3181     return Type::lookup_integer_type("int");
3182   else if (t->map_type() != NULL)
3183     {
3184       if (get_index_type)
3185         return t->map_type()->key_type();
3186       else
3187         return t->map_type()->val_type();
3188     }
3189   else if (t->channel_type() != NULL)
3190     {
3191       if (get_index_type)
3192         return t->channel_type()->element_type();
3193       else
3194         {
3195           if (report_error)
3196             error_at(this->location(),
3197                      "invalid definition of value variable for channel range");
3198           return Type::make_error_type();
3199         }
3200     }
3201   else
3202     {
3203       if (report_error)
3204         error_at(this->location(), "invalid type for range clause");
3205       return Type::make_error_type();
3206     }
3207 }
3208
3209 // EXPR should be a channel.  Return the channel's element type.
3210
3211 Type*
3212 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3213 {
3214   Type* t = expr->type();
3215   if (t->channel_type() != NULL)
3216     return t->channel_type()->element_type();
3217   else
3218     {
3219       if (report_error)
3220         error_at(this->location(), "expected channel");
3221       return Type::make_error_type();
3222     }
3223 }
3224
3225 // Return the type of the Variable.  This may be called before
3226 // Variable::determine_type is called, which means that we may need to
3227 // get the type from the initializer.  FIXME: If we combine lowering
3228 // with type determination, then this should be unnecessary.
3229
3230 Type*
3231 Variable::type()
3232 {
3233   // A variable in a type switch with a nil case will have the wrong
3234   // type here.  This gets fixed up in determine_type, below.
3235   Type* type = this->type_;
3236   Expression* init = this->init_;
3237   if (this->is_type_switch_var_
3238       && this->type_->is_nil_constant_as_type())
3239     {
3240       Type_guard_expression* tge = this->init_->type_guard_expression();
3241       gcc_assert(tge != NULL);
3242       init = tge->expr();
3243       type = NULL;
3244     }
3245
3246   if (this->seen_)
3247     {
3248       if (this->type_ == NULL || !this->type_->is_error_type())
3249         {
3250           error_at(this->location_, "variable initializer refers to itself");
3251           this->type_ = Type::make_error_type();
3252         }
3253       return this->type_;
3254     }
3255
3256   this->seen_ = true;
3257
3258   if (type != NULL)
3259     ;
3260   else if (this->type_from_init_tuple_)
3261     type = this->type_from_tuple(init, false);
3262   else if (this->type_from_range_index_ || this->type_from_range_value_)
3263     type = this->type_from_range(init, this->type_from_range_index_, false);
3264   else if (this->type_from_chan_element_)
3265     type = this->type_from_chan_element(init, false);
3266   else
3267     {
3268       gcc_assert(init != NULL);
3269       type = init->type();
3270       gcc_assert(type != NULL);
3271
3272       // Variables should not have abstract types.
3273       if (type->is_abstract())
3274         type = type->make_non_abstract_type();
3275
3276       if (type->is_void_type())
3277         type = Type::make_error_type();
3278     }
3279
3280   this->seen_ = false;
3281
3282   return type;
3283 }
3284
3285 // Fetch the type from a const pointer, in which case it should have
3286 // been set already.
3287
3288 Type*
3289 Variable::type() const
3290 {
3291   gcc_assert(this->type_ != NULL);
3292   return this->type_;
3293 }
3294
3295 // Set the type if necessary.
3296
3297 void
3298 Variable::determine_type()
3299 {
3300   // A variable in a type switch with a nil case will have the wrong
3301   // type here.  It will have an initializer which is a type guard.
3302   // We want to initialize it to the value without the type guard, and
3303   // use the type of that value as well.
3304   if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3305     {
3306       Type_guard_expression* tge = this->init_->type_guard_expression();
3307       gcc_assert(tge != NULL);
3308       this->type_ = NULL;
3309       this->init_ = tge->expr();
3310     }
3311
3312   if (this->init_ == NULL)
3313     gcc_assert(this->type_ != NULL && !this->type_->is_abstract());
3314   else if (this->type_from_init_tuple_)
3315     {
3316       Expression *init = this->init_;
3317       init->determine_type_no_context();
3318       this->type_ = this->type_from_tuple(init, true);
3319       this->init_ = NULL;
3320     }
3321   else if (this->type_from_range_index_ || this->type_from_range_value_)
3322     {
3323       Expression* init = this->init_;
3324       init->determine_type_no_context();
3325       this->type_ = this->type_from_range(init, this->type_from_range_index_,
3326                                           true);
3327       this->init_ = NULL;
3328     }
3329   else
3330     {
3331       // type_from_chan_element_ should have been cleared during
3332       // lowering.
3333       gcc_assert(!this->type_from_chan_element_);
3334
3335       Type_context context(this->type_, false);
3336       this->init_->determine_type(&context);
3337       if (this->type_ == NULL)
3338         {
3339           Type* type = this->init_->type();
3340           gcc_assert(type != NULL);
3341           if (type->is_abstract())
3342             type = type->make_non_abstract_type();
3343
3344           if (type->is_void_type())
3345             {
3346               error_at(this->location_, "variable has no type");
3347               type = Type::make_error_type();
3348             }
3349           else if (type->is_nil_type())
3350             {
3351               error_at(this->location_, "variable defined to nil type");
3352               type = Type::make_error_type();
3353             }
3354           else if (type->is_call_multiple_result_type())
3355             {
3356               error_at(this->location_,
3357                        "single variable set to multiple value function call");
3358               type = Type::make_error_type();
3359             }
3360
3361           this->type_ = type;
3362         }
3363     }
3364 }
3365
3366 // Export the variable
3367
3368 void
3369 Variable::export_var(Export* exp, const std::string& name) const
3370 {
3371   gcc_assert(this->is_global_);
3372   exp->write_c_string("var ");
3373   exp->write_string(name);
3374   exp->write_c_string(" ");
3375   exp->write_type(this->type());
3376   exp->write_c_string(";\n");
3377 }
3378
3379 // Import a variable.
3380
3381 void
3382 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3383 {
3384   imp->require_c_string("var ");
3385   *pname = imp->read_identifier();
3386   imp->require_c_string(" ");
3387   *ptype = imp->read_type();
3388   imp->require_c_string(";\n");
3389 }
3390
3391 // Class Named_constant.
3392
3393 // Traverse the initializer expression.
3394
3395 int
3396 Named_constant::traverse_expression(Traverse* traverse)
3397 {
3398   return Expression::traverse(&this->expr_, traverse);
3399 }
3400
3401 // Determine the type of the constant.
3402
3403 void
3404 Named_constant::determine_type()
3405 {
3406   if (this->type_ != NULL)
3407     {
3408       Type_context context(this->type_, false);
3409       this->expr_->determine_type(&context);
3410     }
3411   else
3412     {
3413       // A constant may have an abstract type.
3414       Type_context context(NULL, true);
3415       this->expr_->determine_type(&context);
3416       this->type_ = this->expr_->type();
3417       gcc_assert(this->type_ != NULL);
3418     }
3419 }
3420
3421 // Indicate that we found and reported an error for this constant.
3422
3423 void
3424 Named_constant::set_error()
3425 {
3426   this->type_ = Type::make_error_type();
3427   this->expr_ = Expression::make_error(this->location_);
3428 }
3429
3430 // Export a constant.
3431
3432 void
3433 Named_constant::export_const(Export* exp, const std::string& name) const
3434 {
3435   exp->write_c_string("const ");
3436   exp->write_string(name);
3437   exp->write_c_string(" ");
3438   if (!this->type_->is_abstract())
3439     {
3440       exp->write_type(this->type_);
3441       exp->write_c_string(" ");
3442     }
3443   exp->write_c_string("= ");
3444   this->expr()->export_expression(exp);
3445   exp->write_c_string(";\n");
3446 }
3447
3448 // Import a constant.
3449
3450 void
3451 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3452                              Expression** pexpr)
3453 {
3454   imp->require_c_string("const ");
3455   *pname = imp->read_identifier();
3456   imp->require_c_string(" ");
3457   if (imp->peek_char() == '=')
3458     *ptype = NULL;
3459   else
3460     {
3461       *ptype = imp->read_type();
3462       imp->require_c_string(" ");
3463     }
3464   imp->require_c_string("= ");
3465   *pexpr = Expression::import_expression(imp);
3466   imp->require_c_string(";\n");
3467 }
3468
3469 // Add a method.
3470
3471 Named_object*
3472 Type_declaration::add_method(const std::string& name, Function* function)
3473 {
3474   Named_object* ret = Named_object::make_function(name, NULL, function);
3475   this->methods_.push_back(ret);
3476   return ret;
3477 }
3478
3479 // Add a method declaration.
3480
3481 Named_object*
3482 Type_declaration::add_method_declaration(const std::string&  name,
3483                                          Function_type* type,
3484                                          source_location location)
3485 {
3486   Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3487                                                               location);
3488   this->methods_.push_back(ret);
3489   return ret;
3490 }
3491
3492 // Return whether any methods ere defined.
3493
3494 bool
3495 Type_declaration::has_methods() const
3496 {
3497   return !this->methods_.empty();
3498 }
3499
3500 // Define methods for the real type.
3501
3502 void
3503 Type_declaration::define_methods(Named_type* nt)
3504 {
3505   for (Methods::const_iterator p = this->methods_.begin();
3506        p != this->methods_.end();
3507        ++p)
3508     nt->add_existing_method(*p);
3509 }
3510
3511 // We are using the type.  Return true if we should issue a warning.
3512
3513 bool
3514 Type_declaration::using_type()
3515 {
3516   bool ret = !this->issued_warning_;
3517   this->issued_warning_ = true;
3518   return ret;
3519 }
3520
3521 // Class Unknown_name.
3522
3523 // Set the real named object.
3524
3525 void
3526 Unknown_name::set_real_named_object(Named_object* no)
3527 {
3528   gcc_assert(this->real_named_object_ == NULL);
3529   gcc_assert(!no->is_unknown());
3530   this->real_named_object_ = no;
3531 }
3532
3533 // Class Named_object.
3534
3535 Named_object::Named_object(const std::string& name,
3536                            const Package* package,
3537                            Classification classification)
3538   : name_(name), package_(package), classification_(classification),
3539     tree_(NULL)
3540 {
3541   if (Gogo::is_sink_name(name))
3542     gcc_assert(classification == NAMED_OBJECT_SINK);
3543 }
3544
3545 // Make an unknown name.  This is used by the parser.  The name must
3546 // be resolved later.  Unknown names are only added in the current
3547 // package.
3548
3549 Named_object*
3550 Named_object::make_unknown_name(const std::string& name,
3551                                 source_location location)
3552 {
3553   Named_object* named_object = new Named_object(name, NULL,
3554                                                 NAMED_OBJECT_UNKNOWN);
3555   Unknown_name* value = new Unknown_name(location);
3556   named_object->u_.unknown_value = value;
3557   return named_object;
3558 }
3559
3560 // Make a constant.
3561
3562 Named_object*
3563 Named_object::make_constant(const Typed_identifier& tid,
3564                             const Package* package, Expression* expr,
3565                             int iota_value)
3566 {
3567   Named_object* named_object = new Named_object(tid.name(), package,
3568                                                 NAMED_OBJECT_CONST);
3569   Named_constant* named_constant = new Named_constant(tid.type(), expr,
3570                                                       iota_value,
3571                                                       tid.location());
3572   named_object->u_.const_value = named_constant;
3573   return named_object;
3574 }
3575
3576 // Make a named type.
3577
3578 Named_object*
3579 Named_object::make_type(const std::string& name, const Package* package,
3580                         Type* type, source_location location)
3581 {
3582   Named_object* named_object = new Named_object(name, package,
3583                                                 NAMED_OBJECT_TYPE);
3584   Named_type* named_type = Type::make_named_type(named_object, type, location);
3585   named_object->u_.type_value = named_type;
3586   return named_object;
3587 }
3588
3589 // Make a type declaration.
3590
3591 Named_object*
3592 Named_object::make_type_declaration(const std::string& name,
3593                                     const Package* package,
3594                                     source_location location)
3595 {
3596   Named_object* named_object = new Named_object(name, package,
3597                                                 NAMED_OBJECT_TYPE_DECLARATION);
3598   Type_declaration* type_declaration = new Type_declaration(location);
3599   named_object->u_.type_declaration = type_declaration;
3600   return named_object;
3601 }
3602
3603 // Make a variable.
3604
3605 Named_object*
3606 Named_object::make_variable(const std::string& name, const Package* package,
3607                             Variable* variable)
3608 {
3609   Named_object* named_object = new Named_object(name, package,
3610                                                 NAMED_OBJECT_VAR);
3611   named_object->u_.var_value = variable;
3612   return named_object;
3613 }
3614
3615 // Make a result variable.
3616
3617 Named_object*
3618 Named_object::make_result_variable(const std::string& name,
3619                                    Result_variable* result)
3620 {
3621   Named_object* named_object = new Named_object(name, NULL,
3622                                                 NAMED_OBJECT_RESULT_VAR);
3623   named_object->u_.result_var_value = result;
3624   return named_object;
3625 }
3626
3627 // Make a sink.  This is used for the special blank identifier _.
3628
3629 Named_object*
3630 Named_object::make_sink()
3631 {
3632   return new Named_object("_", NULL, NAMED_OBJECT_SINK);
3633 }
3634
3635 // Make a named function.
3636
3637 Named_object*
3638 Named_object::make_function(const std::string& name, const Package* package,
3639                             Function* function)
3640 {
3641   Named_object* named_object = new Named_object(name, package,
3642                                                 NAMED_OBJECT_FUNC);
3643   named_object->u_.func_value = function;
3644   return named_object;
3645 }
3646
3647 // Make a function declaration.
3648
3649 Named_object*
3650 Named_object::make_function_declaration(const std::string& name,
3651                                         const Package* package,
3652                                         Function_type* fntype,
3653                                         source_location location)
3654 {
3655   Named_object* named_object = new Named_object(name, package,
3656                                                 NAMED_OBJECT_FUNC_DECLARATION);
3657   Function_declaration *func_decl = new Function_declaration(fntype, location);
3658   named_object->u_.func_declaration_value = func_decl;
3659   return named_object;
3660 }
3661
3662 // Make a package.
3663
3664 Named_object*
3665 Named_object::make_package(const std::string& alias, Package* package)
3666 {
3667   Named_object* named_object = new Named_object(alias, NULL,
3668                                                 NAMED_OBJECT_PACKAGE);
3669   named_object->u_.package_value = package;
3670   return named_object;
3671 }
3672
3673 // Return the name to use in an error message.
3674
3675 std::string
3676 Named_object::message_name() const
3677 {
3678   if (this->package_ == NULL)
3679     return Gogo::message_name(this->name_);
3680   std::string ret = Gogo::message_name(this->package_->name());
3681   ret += '.';
3682   ret += Gogo::message_name(this->name_);
3683   return ret;
3684 }
3685
3686 // Set the type when a declaration is defined.
3687
3688 void
3689 Named_object::set_type_value(Named_type* named_type)
3690 {
3691   gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
3692   Type_declaration* td = this->u_.type_declaration;
3693   td->define_methods(named_type);
3694   Named_object* in_function = td->in_function();
3695   if (in_function != NULL)
3696     named_type->set_in_function(in_function);
3697   delete td;
3698   this->classification_ = NAMED_OBJECT_TYPE;
3699   this->u_.type_value = named_type;
3700 }
3701
3702 // Define a function which was previously declared.
3703
3704 void
3705 Named_object::set_function_value(Function* function)
3706 {
3707   gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
3708   this->classification_ = NAMED_OBJECT_FUNC;
3709   // FIXME: We should free the old value.
3710   this->u_.func_value = function;
3711 }
3712
3713 // Declare an unknown object as a type declaration.
3714
3715 void
3716 Named_object::declare_as_type()
3717 {
3718   gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
3719   Unknown_name* unk = this->u_.unknown_value;
3720   this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
3721   this->u_.type_declaration = new Type_declaration(unk->location());
3722   delete unk;
3723 }
3724
3725 // Return the location of a named object.
3726
3727 source_location
3728 Named_object::location() const
3729 {
3730   switch (this->classification_)
3731     {
3732     default:
3733     case NAMED_OBJECT_UNINITIALIZED:
3734       gcc_unreachable();
3735
3736     case NAMED_OBJECT_UNKNOWN:
3737       return this->unknown_value()->location();
3738
3739     case NAMED_OBJECT_CONST:
3740       return this->const_value()->location();
3741
3742     case NAMED_OBJECT_TYPE:
3743       return this->type_value()->location();
3744
3745     case NAMED_OBJECT_TYPE_DECLARATION:
3746       return this->type_declaration_value()->location();
3747
3748     case NAMED_OBJECT_VAR:
3749       return this->var_value()->location();
3750
3751     case NAMED_OBJECT_RESULT_VAR:
3752       return this->result_var_value()->function()->location();
3753
3754     case NAMED_OBJECT_SINK:
3755       gcc_unreachable();
3756
3757     case NAMED_OBJECT_FUNC:
3758       return this->func_value()->location();
3759
3760     case NAMED_OBJECT_FUNC_DECLARATION:
3761       return this->func_declaration_value()->location();
3762
3763     case NAMED_OBJECT_PACKAGE:
3764       return this->package_value()->location();
3765     }
3766 }
3767
3768 // Export a named object.
3769
3770 void
3771 Named_object::export_named_object(Export* exp) const
3772 {
3773   switch (this->classification_)
3774     {
3775     default:
3776     case NAMED_OBJECT_UNINITIALIZED:
3777     case NAMED_OBJECT_UNKNOWN:
3778       gcc_unreachable();
3779
3780     case NAMED_OBJECT_CONST:
3781       this->const_value()->export_const(exp, this->name_);
3782       break;
3783
3784     case NAMED_OBJECT_TYPE:
3785       this->type_value()->export_named_type(exp, this->name_);
3786       break;
3787
3788     case NAMED_OBJECT_TYPE_DECLARATION:
3789       error_at(this->type_declaration_value()->location(),
3790                "attempt to export %<%s%> which was declared but not defined",
3791                this->message_name().c_str());
3792       break;
3793
3794     case NAMED_OBJECT_FUNC_DECLARATION:
3795       this->func_declaration_value()->export_func(exp, this->name_);
3796       break;
3797
3798     case NAMED_OBJECT_VAR:
3799       this->var_value()->export_var(exp, this->name_);
3800       break;
3801
3802     case NAMED_OBJECT_RESULT_VAR:
3803     case NAMED_OBJECT_SINK:
3804       gcc_unreachable();
3805
3806     case NAMED_OBJECT_FUNC:
3807       this->func_value()->export_func(exp, this->name_);
3808       break;
3809     }
3810 }
3811
3812 // Class Bindings.
3813
3814 Bindings::Bindings(Bindings* enclosing)
3815   : enclosing_(enclosing), named_objects_(), bindings_()
3816 {
3817 }
3818
3819 // Clear imports.
3820
3821 void
3822 Bindings::clear_file_scope()
3823 {
3824   Contour::iterator p = this->bindings_.begin();
3825   while (p != this->bindings_.end())
3826     {
3827       bool keep;
3828       if (p->second->package() != NULL)
3829         keep = false;
3830       else if (p->second->is_package())
3831         keep = false;
3832       else if (p->second->is_function()
3833                && !p->second->func_value()->type()->is_method()
3834                && Gogo::unpack_hidden_name(p->second->name()) == "init")
3835         keep = false;
3836       else
3837         keep = true;
3838
3839       if (keep)
3840         ++p;
3841       else
3842         p = this->bindings_.erase(p);
3843     }
3844 }
3845
3846 // Look up a symbol.
3847
3848 Named_object*
3849 Bindings::lookup(const std::string& name) const
3850 {
3851   Contour::const_iterator p = this->bindings_.find(name);
3852   if (p != this->bindings_.end())
3853     return p->second->resolve();
3854   else if (this->enclosing_ != NULL)
3855     return this->enclosing_->lookup(name);
3856   else
3857     return NULL;
3858 }
3859
3860 // Look up a symbol locally.
3861
3862 Named_object*
3863 Bindings::lookup_local(const std::string& name) const
3864 {
3865   Contour::const_iterator p = this->bindings_.find(name);
3866   if (p == this->bindings_.end())
3867     return NULL;
3868   return p->second;
3869 }
3870
3871 // Remove an object from a set of bindings.  This is used for a
3872 // special case in thunks for functions which call recover.
3873
3874 void
3875 Bindings::remove_binding(Named_object* no)
3876 {
3877   Contour::iterator pb = this->bindings_.find(no->name());
3878   gcc_assert(pb != this->bindings_.end());
3879   this->bindings_.erase(pb);
3880   for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
3881        pn != this->named_objects_.end();
3882        ++pn)
3883     {
3884       if (*pn == no)
3885         {
3886           this->named_objects_.erase(pn);
3887           return;
3888         }
3889     }
3890   gcc_unreachable();
3891 }
3892
3893 // Add a method to the list of objects.  This is not added to the
3894 // lookup table.  This is so that we have a single list of objects
3895 // declared at the top level, which we walk through when it's time to
3896 // convert to trees.
3897
3898 void
3899 Bindings::add_method(Named_object* method)
3900 {
3901   this->named_objects_.push_back(method);
3902 }
3903
3904 // Add a generic Named_object to a Contour.
3905
3906 Named_object*
3907 Bindings::add_named_object_to_contour(Contour* contour,
3908                                       Named_object* named_object)
3909 {
3910   gcc_assert(named_object == named_object->resolve());
3911   const std::string& name(named_object->name());
3912   gcc_assert(!Gogo::is_sink_name(name));
3913
3914   std::pair<Contour::iterator, bool> ins =
3915     contour->insert(std::make_pair(name, named_object));
3916   if (!ins.second)
3917     {
3918       // The name was already there.
3919       if (named_object->package() != NULL
3920           && ins.first->second->package() == named_object->package()
3921           && (ins.first->second->classification()
3922               == named_object->classification()))
3923         {
3924           // This is a second import of the same object.
3925           return ins.first->second;
3926         }
3927       ins.first->second = this->new_definition(ins.first->second,
3928                                                named_object);
3929       return ins.first->second;
3930     }
3931   else
3932     {
3933       // Don't push declarations on the list.  We push them on when
3934       // and if we find the definitions.  That way we genericize the
3935       // functions in order.
3936       if (!named_object->is_type_declaration()
3937           && !named_object->is_function_declaration()
3938           && !named_object->is_unknown())
3939         this->named_objects_.push_back(named_object);
3940       return named_object;
3941     }
3942 }
3943
3944 // We had an existing named object OLD_OBJECT, and we've seen a new
3945 // one NEW_OBJECT with the same name.  FIXME: This does not free the
3946 // new object when we don't need it.
3947
3948 Named_object*
3949 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
3950 {
3951   std::string reason;
3952   switch (old_object->classification())
3953     {
3954     default:
3955     case Named_object::NAMED_OBJECT_UNINITIALIZED:
3956       gcc_unreachable();
3957
3958     case Named_object::NAMED_OBJECT_UNKNOWN:
3959       {
3960         Named_object* real = old_object->unknown_value()->real_named_object();
3961         if (real != NULL)
3962           return this->new_definition(real, new_object);
3963         gcc_assert(!new_object->is_unknown());
3964         old_object->unknown_value()->set_real_named_object(new_object);
3965         if (!new_object->is_type_declaration()
3966             && !new_object->is_function_declaration())
3967           this->named_objects_.push_back(new_object);
3968         return new_object;
3969       }
3970
3971     case Named_object::NAMED_OBJECT_CONST:
3972       break;
3973
3974     case Named_object::NAMED_OBJECT_TYPE:
3975       if (new_object->is_type_declaration())
3976         return old_object;
3977       break;
3978
3979     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3980       if (new_object->is_type_declaration())
3981         return old_object;
3982       if (new_object->is_type())
3983         {
3984           old_object->set_type_value(new_object->type_value());
3985           new_object->type_value()->set_named_object(old_object);
3986           this->named_objects_.push_back(old_object);
3987           return old_object;
3988         }
3989       break;
3990
3991     case Named_object::NAMED_OBJECT_VAR:
3992     case Named_object::NAMED_OBJECT_RESULT_VAR:
3993       break;
3994
3995     case Named_object::NAMED_OBJECT_SINK:
3996       gcc_unreachable();
3997
3998     case Named_object::NAMED_OBJECT_FUNC:
3999       if (new_object->is_function_declaration())
4000         {
4001           if (!new_object->func_declaration_value()->asm_name().empty())
4002             sorry("__asm__ for function definitions");
4003           Function_type* old_type = old_object->func_value()->type();
4004           Function_type* new_type =
4005             new_object->func_declaration_value()->type();
4006           if (old_type->is_valid_redeclaration(new_type, &reason))
4007             return old_object;
4008         }
4009       break;
4010
4011     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4012       {
4013         Function_type* old_type = old_object->func_declaration_value()->type();
4014         if (new_object->is_function_declaration())
4015           {
4016             Function_type* new_type =
4017               new_object->func_declaration_value()->type();
4018             if (old_type->is_valid_redeclaration(new_type, &reason))
4019               return old_object;
4020           }
4021         if (new_object->is_function())
4022           {
4023             Function_type* new_type = new_object->func_value()->type();
4024             if (old_type->is_valid_redeclaration(new_type, &reason))
4025               {
4026                 if (!old_object->func_declaration_value()->asm_name().empty())
4027                   sorry("__asm__ for function definitions");
4028                 old_object->set_function_value(new_object->func_value());
4029                 this->named_objects_.push_back(old_object);
4030                 return old_object;
4031               }
4032           }
4033       }
4034       break;
4035
4036     case Named_object::NAMED_OBJECT_PACKAGE:
4037       if (new_object->is_package()
4038           && (old_object->package_value()->name()
4039               == new_object->package_value()->name()))
4040         return old_object;
4041
4042       break;
4043     }
4044
4045   std::string n = old_object->message_name();
4046   if (reason.empty())
4047     error_at(new_object->location(), "redefinition of %qs", n.c_str());
4048   else
4049     error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4050              reason.c_str());
4051
4052   inform(old_object->location(), "previous definition of %qs was here",
4053          n.c_str());
4054
4055   return old_object;
4056 }
4057
4058 // Add a named type.
4059
4060 Named_object*
4061 Bindings::add_named_type(Named_type* named_type)
4062 {
4063   return this->add_named_object(named_type->named_object());
4064 }
4065
4066 // Add a function.
4067
4068 Named_object*
4069 Bindings::add_function(const std::string& name, const Package* package,
4070                        Function* function)
4071 {
4072   return this->add_named_object(Named_object::make_function(name, package,
4073                                                             function));
4074 }
4075
4076 // Add a function declaration.
4077
4078 Named_object*
4079 Bindings::add_function_declaration(const std::string& name,
4080                                    const Package* package,
4081                                    Function_type* type,
4082                                    source_location location)
4083 {
4084   Named_object* no = Named_object::make_function_declaration(name, package,
4085                                                              type, location);
4086   return this->add_named_object(no);
4087 }
4088
4089 // Define a type which was previously declared.
4090
4091 void
4092 Bindings::define_type(Named_object* no, Named_type* type)
4093 {
4094   no->set_type_value(type);
4095   this->named_objects_.push_back(no);
4096 }
4097
4098 // Traverse bindings.
4099
4100 int
4101 Bindings::traverse(Traverse* traverse, bool is_global)
4102 {
4103   unsigned int traverse_mask = traverse->traverse_mask();
4104
4105   // We don't use an iterator because we permit the traversal to add
4106   // new global objects.
4107   for (size_t i = 0; i < this->named_objects_.size(); ++i)
4108     {
4109       Named_object* p = this->named_objects_[i];
4110       switch (p->classification())
4111         {
4112         case Named_object::NAMED_OBJECT_CONST:
4113           if ((traverse_mask & Traverse::traverse_constants) != 0)
4114             {
4115               if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4116                 return TRAVERSE_EXIT;
4117             }
4118           if ((traverse_mask & Traverse::traverse_types) != 0
4119               || (traverse_mask & Traverse::traverse_expressions) != 0)
4120             {
4121               Type* t = p->const_value()->type();
4122               if (t != NULL
4123                   && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4124                 return TRAVERSE_EXIT;
4125             }
4126           if ((traverse_mask & Traverse::traverse_expressions) != 0)
4127             {
4128               if (p->const_value()->traverse_expression(traverse)
4129                   == TRAVERSE_EXIT)
4130                 return TRAVERSE_EXIT;
4131             }
4132           break;
4133
4134         case Named_object::NAMED_OBJECT_VAR:
4135         case Named_object::NAMED_OBJECT_RESULT_VAR:
4136           if ((traverse_mask & Traverse::traverse_variables) != 0)
4137             {
4138               if (traverse->variable(p) == TRAVERSE_EXIT)
4139                 return TRAVERSE_EXIT;
4140             }
4141           if (((traverse_mask & Traverse::traverse_types) != 0
4142                || (traverse_mask & Traverse::traverse_expressions) != 0)
4143               && (p->is_result_variable()
4144                   || p->var_value()->has_type()))
4145             {
4146               Type* t = (p->is_variable()
4147                          ? p->var_value()->type()
4148                          : p->result_var_value()->type());
4149               if (t != NULL
4150                   && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4151                 return TRAVERSE_EXIT;
4152             }
4153           if (p->is_variable()
4154               && (traverse_mask & Traverse::traverse_expressions) != 0)
4155             {
4156               if (p->var_value()->traverse_expression(traverse)
4157                   == TRAVERSE_EXIT)
4158                 return TRAVERSE_EXIT;
4159             }
4160           break;
4161
4162         case Named_object::NAMED_OBJECT_FUNC:
4163           if ((traverse_mask & Traverse::traverse_functions) != 0)
4164             {
4165               int t = traverse->function(p);
4166               if (t == TRAVERSE_EXIT)
4167                 return TRAVERSE_EXIT;
4168               else if (t == TRAVERSE_SKIP_COMPONENTS)
4169                 break;
4170             }
4171
4172           if ((traverse_mask
4173                & (Traverse::traverse_variables
4174                   | Traverse::traverse_constants
4175                   | Traverse::traverse_functions
4176                   | Traverse::traverse_blocks
4177                   | Traverse::traverse_statements
4178                   | Traverse::traverse_expressions
4179                   | Traverse::traverse_types)) != 0)
4180             {
4181               if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4182                 return TRAVERSE_EXIT;
4183             }
4184           break;
4185
4186         case Named_object::NAMED_OBJECT_PACKAGE:
4187           // These are traversed in Gogo::traverse.
4188           gcc_assert(is_global);
4189           break;
4190
4191         case Named_object::NAMED_OBJECT_TYPE:
4192           if ((traverse_mask & Traverse::traverse_types) != 0
4193               || (traverse_mask & Traverse::traverse_expressions) != 0)
4194             {
4195               if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4196                 return TRAVERSE_EXIT;
4197             }
4198           break;
4199
4200         case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4201         case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4202         case Named_object::NAMED_OBJECT_UNKNOWN:
4203           break;
4204
4205         case Named_object::NAMED_OBJECT_SINK:
4206         default:
4207           gcc_unreachable();
4208         }
4209     }
4210
4211   return TRAVERSE_CONTINUE;
4212 }
4213
4214 // Class Package.
4215
4216 Package::Package(const std::string& name, const std::string& unique_prefix,
4217                  source_location location)
4218   : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4219     priority_(0), location_(location), used_(false), is_imported_(false),
4220     uses_sink_alias_(false)
4221 {
4222   gcc_assert(!name.empty() && !unique_prefix.empty());
4223 }
4224
4225 // Set the priority.  We may see multiple priorities for an imported
4226 // package; we want to use the largest one.
4227
4228 void
4229 Package::set_priority(int priority)
4230 {
4231   if (priority > this->priority_)
4232     this->priority_ = priority;
4233 }
4234
4235 // Determine types of constants.  Everything else in a package
4236 // (variables, function declarations) should already have a fixed
4237 // type.  Constants may have abstract types.
4238
4239 void
4240 Package::determine_types()
4241 {
4242   Bindings* bindings = this->bindings_;
4243   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4244        p != bindings->end_definitions();
4245        ++p)
4246     {
4247       if ((*p)->is_const())
4248         (*p)->const_value()->determine_type();
4249     }
4250 }
4251
4252 // Class Traverse.
4253
4254 // Destructor.
4255
4256 Traverse::~Traverse()
4257 {
4258   if (this->types_seen_ != NULL)
4259     delete this->types_seen_;
4260   if (this->expressions_seen_ != NULL)
4261     delete this->expressions_seen_;
4262 }
4263
4264 // Record that we are looking at a type, and return true if we have
4265 // already seen it.
4266
4267 bool
4268 Traverse::remember_type(const Type* type)
4269 {
4270   if (type->is_error_type())
4271     return true;
4272   gcc_assert((this->traverse_mask() & traverse_types) != 0
4273              || (this->traverse_mask() & traverse_expressions) != 0);
4274   // We only have to remember named types, as they are the only ones
4275   // we can see multiple times in a traversal.
4276   if (type->classification() != Type::TYPE_NAMED)
4277     return false;
4278   if (this->types_seen_ == NULL)
4279     this->types_seen_ = new Types_seen();
4280   std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4281   return !ins.second;
4282 }
4283
4284 // Record that we are looking at an expression, and return true if we
4285 // have already seen it.
4286
4287 bool
4288 Traverse::remember_expression(const Expression* expression)
4289 {
4290   gcc_assert((this->traverse_mask() & traverse_types) != 0
4291              || (this->traverse_mask() & traverse_expressions) != 0);
4292   if (this->expressions_seen_ == NULL)
4293     this->expressions_seen_ = new Expressions_seen();
4294   std::pair<Expressions_seen::iterator, bool> ins =
4295     this->expressions_seen_->insert(expression);
4296   return !ins.second;
4297 }
4298
4299 // The default versions of these functions should never be called: the
4300 // traversal mask indicates which functions may be called.
4301
4302 int
4303 Traverse::variable(Named_object*)
4304 {
4305   gcc_unreachable();
4306 }
4307
4308 int
4309 Traverse::constant(Named_object*, bool)
4310 {
4311   gcc_unreachable();
4312 }
4313
4314 int
4315 Traverse::function(Named_object*)
4316 {
4317   gcc_unreachable();
4318 }
4319
4320 int
4321 Traverse::block(Block*)
4322 {
4323   gcc_unreachable();
4324 }
4325
4326 int
4327 Traverse::statement(Block*, size_t*, Statement*)
4328 {
4329   gcc_unreachable();
4330 }
4331
4332 int
4333 Traverse::expression(Expression**)
4334 {
4335   gcc_unreachable();
4336 }
4337
4338 int
4339 Traverse::type(Type*)
4340 {
4341   gcc_unreachable();
4342 }