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