1 // import.cc -- Go frontend import declarations.
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.
10 #include "simple-object.h"
22 // The list of paths we search for import files.
24 static std::vector<std::string> search_path;
26 // Add a directory to the search path. This is called from the option
27 // handling language hook.
31 go_add_search_path(const char* path)
33 search_path.push_back(std::string(path));
36 // The name used for parameters, receivers, and results in imported
39 const char* const Import::import_marker = "*imported*";
41 // Find import data. This searches the file system for FILENAME and
42 // returns a pointer to a Stream object to read the data that it
43 // exports. If the file is not found, it returns NULL.
45 // When FILENAME is not an absolute path and does not start with ./ or
46 // ../, we use the search path provided by -I and -L options.
48 // When FILENAME does not exist, we try modifying FILENAME to find the
49 // file. We use the first of these which exists:
50 // * We append ".gox".
51 // * We turn the base of FILENAME into libFILENAME.so.
52 // * We turn the base of FILENAME into libFILENAME.a.
55 // When using a search path, we apply each of these transformations at
56 // each entry on the search path before moving on to the next entry.
57 // If the file exists, but does not contain any Go export data, we
58 // stop; we do not keep looking for another file with the same name
59 // later in the search path.
62 Import::open_package(const std::string& filename, Location location)
65 if (IS_ABSOLUTE_PATH(filename))
67 else if (filename[0] == '.' && IS_DIR_SEPARATOR(filename[1]))
69 else if (filename[0] == '.'
71 && IS_DIR_SEPARATOR(filename[2]))
77 for (std::vector<std::string>::const_iterator p = search_path.begin();
78 p != search_path.end();
81 std::string indir = *p;
82 if (!indir.empty() && indir[indir.size() - 1] != '/')
85 Stream* s = Import::try_package_in_directory(indir, location);
91 Stream* s = Import::try_package_in_directory(filename, location);
98 // Try to find the export data for FILENAME.
101 Import::try_package_in_directory(const std::string& filename,
104 std::string found_filename = filename;
105 int fd = open(found_filename.c_str(), O_RDONLY | O_BINARY);
110 if (fstat(fd, &s) >= 0 && S_ISDIR(s.st_mode))
120 if (errno != ENOENT && errno != EISDIR)
121 warning_at(location, 0, "%s: %m", filename.c_str());
123 fd = Import::try_suffixes(&found_filename);
128 // The export data may not be in this file.
129 Stream* s = Import::find_export_data(found_filename, fd, location);
135 error_at(location, "%s exists but does not contain any Go export data",
136 found_filename.c_str());
141 // Given import "*PFILENAME", where *PFILENAME does not exist, try
142 // various suffixes. If we find one, set *PFILENAME to the one we
143 // found. Return the open file descriptor.
146 Import::try_suffixes(std::string* pfilename)
148 std::string filename = *pfilename + ".gox";
149 int fd = open(filename.c_str(), O_RDONLY | O_BINARY);
152 *pfilename = filename;
156 const char* basename = lbasename(pfilename->c_str());
157 size_t basename_pos = basename - pfilename->c_str();
158 filename = pfilename->substr(0, basename_pos) + "lib" + basename + ".so";
159 fd = open(filename.c_str(), O_RDONLY | O_BINARY);
162 *pfilename = filename;
166 filename = pfilename->substr(0, basename_pos) + "lib" + basename + ".a";
167 fd = open(filename.c_str(), O_RDONLY | O_BINARY);
170 *pfilename = filename;
174 filename = *pfilename + ".o";
175 fd = open(filename.c_str(), O_RDONLY | O_BINARY);
178 *pfilename = filename;
185 // Look for export data in the file descriptor FD.
188 Import::find_export_data(const std::string& filename, int fd,
191 // See if we can read this as an object file.
192 Import::Stream* stream = Import::find_object_export_data(filename, fd, 0,
197 const int len = MAX(Export::v1_magic_len, Import::archive_magic_len);
199 if (lseek(fd, 0, SEEK_SET) < 0)
201 error_at(location, "lseek %s failed: %m", filename.c_str());
206 ssize_t c = read(fd, buf, len);
210 // Check for a file containing nothing but Go export data.
211 if (memcmp(buf, Export::v1_magic, Export::v1_magic_len) == 0)
212 return new Stream_from_file(fd);
214 // See if we can read this as an archive.
215 if (Import::is_archive_magic(buf))
216 return Import::find_archive_export_data(filename, fd, location);
221 // Look for export data in a simple_object.
224 Import::find_object_export_data(const std::string& filename,
232 const char *errmsg = go_read_export_data(fd, offset, &buf, &len, &err);
236 error_at(location, "%s: %s", filename.c_str(), errmsg);
238 error_at(location, "%s: %s: %s", filename.c_str(), errmsg,
246 return new Stream_from_buffer(buf, len);
251 // Construct an Import object. We make the builtin_types_ vector
252 // large enough to hold all the builtin types.
254 Import::Import(Stream* stream, Location location)
255 : gogo_(NULL), stream_(stream), location_(location), package_(NULL),
256 add_to_globals_(false),
257 builtin_types_((- SMALLEST_BUILTIN_CODE) + 1),
262 // Import the data in the associated stream.
265 Import::import(Gogo* gogo, const std::string& local_name,
266 bool is_local_name_exported)
268 // Hold on to the Gogo structure. Otherwise we need to pass it
269 // through all the import functions, because we need it when reading
273 // A stream of export data can include data from more than one input
274 // file. Here we loop over each input file.
275 Stream* stream = this->stream_;
276 while (!stream->at_eof() && !stream->saw_error())
278 // The vector of types is package specific.
279 this->types_.clear();
281 stream->require_bytes(this->location_, Export::v1_magic,
282 Export::v1_magic_len);
284 this->require_c_string("package ");
285 std::string package_name = this->read_identifier();
286 this->require_c_string(";\n");
288 this->require_c_string("prefix ");
289 std::string unique_prefix = this->read_identifier();
290 this->require_c_string(";\n");
292 this->package_ = gogo->add_imported_package(package_name, local_name,
293 is_local_name_exported,
296 &this->add_to_globals_);
297 if (this->package_ == NULL)
299 stream->set_saw_error();
303 this->require_c_string("priority ");
304 std::string priority_string = this->read_identifier();
306 if (!this->string_to_int(priority_string, false, &prio))
308 this->package_->set_priority(prio);
309 this->require_c_string(";\n");
311 if (stream->match_c_string("import "))
312 this->read_import_init_fns(gogo);
314 // Loop over all the input data for this package.
315 while (!stream->saw_error())
317 if (stream->match_c_string("const "))
318 this->import_const();
319 else if (stream->match_c_string("type "))
321 else if (stream->match_c_string("var "))
323 else if (stream->match_c_string("func "))
324 this->import_func(this->package_);
325 else if (stream->match_c_string("checksum "))
329 error_at(this->location_,
330 ("error in import data at %d: "
331 "expected %<const%>, %<type%>, %<var%>, "
332 "%<func%>, or %<checksum%>"),
334 stream->set_saw_error();
339 // We currently ignore the checksum. In the future we could
340 // store the checksum somewhere in the generated object and then
341 // verify that the checksum matches at link time or at dynamic
343 this->require_c_string("checksum ");
344 stream->advance(Export::v1_checksum_len * 2);
345 this->require_c_string(";\n");
348 return this->package_;
351 // Read the list of import control functions.
354 Import::read_import_init_fns(Gogo* gogo)
356 this->require_c_string("import");
357 while (!this->match_c_string(";"))
359 this->require_c_string(" ");
360 std::string package_name = this->read_identifier();
361 this->require_c_string(" ");
362 std::string init_name = this->read_identifier();
363 this->require_c_string(" ");
364 std::string prio_string = this->read_identifier();
366 if (!this->string_to_int(prio_string, false, &prio))
368 gogo->add_import_init_fn(package_name, init_name, prio);
370 this->require_c_string(";\n");
373 // Import a constant.
376 Import::import_const()
381 Named_constant::import_const(this, &name, &type, &expr);
382 Typed_identifier tid(name, type, this->location_);
383 Named_object* no = this->package_->add_constant(tid, expr);
384 if (this->add_to_globals_)
385 this->gogo_->add_named_object(no);
391 Import::import_type()
394 Named_type::import_named_type(this, &type);
396 // The named type has been added to the package by the type import
397 // process. Here we need to make it visible to the parser, and it
398 // to the global bindings if necessary.
399 type->set_is_visible();
401 if (this->add_to_globals_)
402 this->gogo_->add_named_type(type);
405 // Import a variable.
412 Variable::import_var(this, &name, &type);
413 Variable* var = new Variable(type, NULL, true, false, false,
416 no = this->package_->add_variable(name, var);
417 if (this->add_to_globals_)
418 this->gogo_->add_named_object(no);
421 // Import a function into PACKAGE. PACKAGE is normally
422 // THIS->PACKAGE_, but it will be different for a method associated
423 // with a type defined in a different package.
426 Import::import_func(Package* package)
429 Typed_identifier* receiver;
430 Typed_identifier_list* parameters;
431 Typed_identifier_list* results;
433 Function::import_func(this, &name, &receiver, ¶meters, &results,
435 Function_type *fntype = Type::make_function_type(receiver, parameters,
436 results, this->location_);
438 fntype->set_is_varargs();
440 Location loc = this->location_;
442 if (fntype->is_method())
444 Type* rtype = receiver->type()->deref();
445 if (rtype->is_error_type())
447 Named_type* named_rtype = rtype->named_type();
448 go_assert(named_rtype != NULL);
449 no = named_rtype->add_method_declaration(name, package, fntype, loc);
453 no = package->add_function_declaration(name, fntype, loc);
454 if (this->add_to_globals_)
455 this->gogo_->add_named_object(no);
460 // Read a type in the import stream. This records the type by the
461 // type index. If the type is named, it registers the name, but marks
467 Stream* stream = this->stream_;
468 this->require_c_string("<type ");
474 c = stream->get_char();
475 if (c != '-' && (c < '0' || c > '9'))
481 if (!this->string_to_int(number, true, &index))
482 return Type::make_error_type();
486 // This type was already defined.
488 ? (static_cast<size_t>(- index) >= this->builtin_types_.size()
489 || this->builtin_types_[- index] == NULL)
490 : (static_cast<size_t>(index) >= this->types_.size()
491 || this->types_[index] == NULL))
493 error_at(this->location_,
494 "error in import data at %d: bad type index %d",
495 stream->pos(), index);
496 stream->set_saw_error();
497 return Type::make_error_type();
500 return index < 0 ? this->builtin_types_[- index] : this->types_[index];
505 if (!stream->saw_error())
506 error_at(this->location_,
507 "error in import data at %d: expect %< %> or %<>%>'",
509 stream->set_saw_error();
511 return Type::make_error_type();
515 || (static_cast<size_t>(index) < this->types_.size()
516 && this->types_[index] != NULL))
518 error_at(this->location_,
519 "error in import data at %d: type index already defined",
521 stream->set_saw_error();
522 return Type::make_error_type();
525 if (static_cast<size_t>(index) >= this->types_.size())
527 int newsize = std::max(static_cast<size_t>(index) + 1,
528 this->types_.size() * 2);
529 this->types_.resize(newsize, NULL);
532 if (stream->peek_char() != '"')
534 Type* type = Type::import_type(this);
535 this->require_c_string(">");
536 this->types_[index] = type;
540 // This type has a name.
543 std::string type_name;
544 while ((c = stream->get_char()) != '"')
547 // If this type is in the current package, the name will be
548 // .PREFIX.PACKAGE.NAME or simply NAME with no dots. Otherwise, a
549 // non-hidden symbol will be PREFIX.PACKAGE.NAME and a hidden symbol
550 // will be .PREFIX.PACKAGE.NAME.
551 std::string package_name;
552 std::string unique_prefix;
553 if (type_name.find('.') != std::string::npos)
555 bool is_hidden = false;
557 if (type_name[0] == '.')
562 size_t dot1 = type_name.find('.', start);
564 if (dot1 == std::string::npos)
565 dot2 = std::string::npos;
567 dot2 = type_name.find('.', dot1 + 1);
568 if (dot1 == std::string::npos || dot2 == std::string::npos)
570 error_at(this->location_,
571 ("error at import data at %d: missing dot in type name"),
573 stream->set_saw_error();
577 unique_prefix = type_name.substr(start, dot1 - start);
578 package_name = type_name.substr(dot1 + 1, dot2 - (dot1 + 1));
581 type_name.erase(0, dot2 + 1);
584 this->require_c_string(" ");
586 // Declare the type in the appropriate package. If we haven't seen
587 // it before, mark it as invisible. We declare it before we read
588 // the actual definition of the type, since the definition may refer
589 // to the type itself.
591 if (package_name.empty())
592 package = this->package_;
594 package = this->gogo_->register_package(package_name, unique_prefix,
595 Linemap::unknown_location());
597 Named_object* no = package->bindings()->lookup(type_name);
599 no = package->add_type_declaration(type_name, this->location_);
600 else if (!no->is_type_declaration() && !no->is_type())
602 error_at(this->location_, "imported %<%s.%s%> both type and non-type",
603 Gogo::message_name(package->name()).c_str(),
604 Gogo::message_name(type_name).c_str());
605 stream->set_saw_error();
606 return Type::make_error_type();
609 go_assert(no->package() == package);
611 if (this->types_[index] == NULL)
613 if (no->is_type_declaration())
615 // FIXME: It's silly to make a forward declaration every time.
616 this->types_[index] = Type::make_forward_declaration(no);
620 go_assert(no->is_type());
621 this->types_[index] = no->type_value();
625 // If there is no type definition, then this is just a forward
626 // declaration of a type defined in some other file.
628 if (this->match_c_string(">"))
629 type = this->types_[index];
632 type = this->read_type();
634 if (no->is_type_declaration())
636 // We can define the type now.
638 no = package->add_type(type_name, type, this->location_);
639 Named_type* ntype = no->type_value();
641 // This type has not yet been imported.
642 ntype->clear_is_visible();
646 else if (no->is_type())
648 // We have seen this type before. FIXME: it would be a good
649 // idea to check that the two imported types are identical,
650 // but we have not finalized the methds yet, which means
651 // that we can nt reliably compare interface types.
652 type = no->type_value();
654 // Don't change the visibility of the existing type.
657 this->types_[index] = type;
659 // Read the type methods.
660 if (this->match_c_string("\n"))
663 while (this->match_c_string(" func"))
666 this->import_func(package);
671 this->require_c_string(">");
676 // Register the builtin types.
679 Import::register_builtin_types(Gogo* gogo)
681 this->register_builtin_type(gogo, "int8", BUILTIN_INT8);
682 this->register_builtin_type(gogo, "int16", BUILTIN_INT16);
683 this->register_builtin_type(gogo, "int32", BUILTIN_INT32);
684 this->register_builtin_type(gogo, "int64", BUILTIN_INT64);
685 this->register_builtin_type(gogo, "uint8", BUILTIN_UINT8);
686 this->register_builtin_type(gogo, "uint16", BUILTIN_UINT16);
687 this->register_builtin_type(gogo, "uint32", BUILTIN_UINT32);
688 this->register_builtin_type(gogo, "uint64", BUILTIN_UINT64);
689 this->register_builtin_type(gogo, "float32", BUILTIN_FLOAT32);
690 this->register_builtin_type(gogo, "float64", BUILTIN_FLOAT64);
691 this->register_builtin_type(gogo, "complex64", BUILTIN_COMPLEX64);
692 this->register_builtin_type(gogo, "complex128", BUILTIN_COMPLEX128);
693 this->register_builtin_type(gogo, "int", BUILTIN_INT);
694 this->register_builtin_type(gogo, "uint", BUILTIN_UINT);
695 this->register_builtin_type(gogo, "uintptr", BUILTIN_UINTPTR);
696 this->register_builtin_type(gogo, "bool", BUILTIN_BOOL);
697 this->register_builtin_type(gogo, "string", BUILTIN_STRING);
698 this->register_builtin_type(gogo, "error", BUILTIN_ERROR);
701 // Register a single builtin type.
704 Import::register_builtin_type(Gogo* gogo, const char* name, Builtin_code code)
706 Named_object* named_object = gogo->lookup_global(name);
707 go_assert(named_object != NULL && named_object->is_type());
708 int index = - static_cast<int>(code);
710 && static_cast<size_t>(index) < this->builtin_types_.size());
711 this->builtin_types_[index] = named_object->type_value();
714 // Read an identifier from the stream.
717 Import::read_identifier()
720 Stream* stream = this->stream_;
724 c = stream->peek_char();
725 if (c == -1 || c == ' ' || c == ';')
733 // Turn a string into a integer with appropriate error handling.
736 Import::string_to_int(const std::string &s, bool is_neg_ok, int* ret)
739 long prio = strtol(s.c_str(), &end, 10);
740 if (*end != '\0' || prio > 0x7fffffff || (prio < 0 && !is_neg_ok))
742 error_at(this->location_, "invalid integer in import data at %d",
743 this->stream_->pos());
744 this->stream_->set_saw_error();
751 // Class Import::Stream.
753 Import::Stream::Stream()
754 : pos_(0), saw_error_(false)
758 Import::Stream::~Stream()
762 // Return the next character to come from the stream.
765 Import::Stream::peek_char()
768 if (!this->do_peek(1, &read))
770 // Make sure we return an unsigned char, so that we don't get
772 unsigned char ret = *read;
776 // Return true if the next LENGTH characters from the stream match
780 Import::Stream::match_bytes(const char* bytes, size_t length)
783 if (!this->do_peek(length, &read))
785 return memcmp(bytes, read, length) == 0;
788 // Require that the next LENGTH bytes from the stream match BYTES.
791 Import::Stream::require_bytes(Location location, const char* bytes,
795 if (!this->do_peek(length, &read)
796 || memcmp(bytes, read, length) != 0)
798 if (!this->saw_error_)
799 error_at(location, "import error at %d: expected %<%.*s%>",
800 this->pos(), static_cast<int>(length), bytes);
801 this->saw_error_ = true;
804 this->advance(length);
807 // Class Stream_from_file.
809 Stream_from_file::Stream_from_file(int fd)
812 if (lseek(fd, 0, SEEK_SET) != 0)
814 error("lseek failed: %m");
815 this->set_saw_error();
819 Stream_from_file::~Stream_from_file()
827 Stream_from_file::do_peek(size_t length, const char** bytes)
829 if (this->data_.length() <= length)
831 *bytes = this->data_.data();
834 // Don't bother to handle the general case, since we don't need it.
835 go_assert(length < 64);
837 ssize_t got = read(this->fd_, buf, length);
841 if (!this->saw_error())
842 error("read failed: %m");
843 this->set_saw_error();
847 if (lseek(this->fd_, - got, SEEK_CUR) != 0)
849 if (!this->saw_error())
850 error("lseek failed: %m");
851 this->set_saw_error();
855 if (static_cast<size_t>(got) < length)
858 this->data_.assign(buf, got);
860 *bytes = this->data_.data();
867 Stream_from_file::do_advance(size_t skip)
869 if (lseek(this->fd_, skip, SEEK_CUR) != 0)
871 if (!this->saw_error())
872 error("lseek failed: %m");
873 this->set_saw_error();
875 if (!this->data_.empty())
877 if (this->data_.length() < skip)
878 this->data_.erase(0, skip);