"""Implementation of import in Python source code.

Direct imports are not allowed because of dependency issues.  Any required
modules must be injected from an outside source.

Default parameter values cannot be from a module as any injected module will
come after the module has been imported.

====================
References on import
====================
* Language reference
      http://docs.python.org/ref/import.html
* __import__ function
      http://docs.python.org/lib/built-in-funcs.html
* Packages
      http://www.python.org/doc/essays/packages.html
* PEP 235: Import on Case-Insensitive Platforms
      http://www.python.org/dev/peps/pep-0235
* PEP 275: Import Modules from Zip Archives
      http://www.python.org/dev/peps/pep-0273
* PEP 302: New Import Hooks
      http://www.python.org/dev/peps/pep-0302/
* PEP 328: Imports: Multi-line and Absolute/Relative
      http://www.python.org/dev/peps/pep-0328

============
Known Issues
============
* runpy ('-m' command-line option for Python) does not work.
    + Requires get_code to be implemented for loaders.
    + Uses pkgutil.get_loader which fakes a loader if __loader__ is not defined.
    + New loaders do define __loader__ but not get_code, and thus dies on an
      AttributeError.
    + Possible fix
        - Implement optional interface for loaders.
        - Do not have new loaders set __loader__.
            * Might happen because of security issues.
* warnings and stack level.
    + Affected tests
        - test___all__
        - test_imageop
    + 'warnings' assumes that the import code does not show up in the call
      stack.
    + Because import now implemented in Python, import does show up in the
      call stack.
    + Trick of specifying going back in the call stack two levels so warning
      shows up in the caller will cause the warning no longer holds true.
    + Possible fixes
        - Special module deprecation function.
        - Code in warnings.warn to handle special import case.
        - Flag on warnings.warn that warning is for an import and ignore stack
          level argument.
              * Could also infer from type of warning.
* test_pkg
    + Old-style test that compares output.
    + Setting of __loader__ leads to different output.

"""
from __future__ import with_statement

# Injected modules are 'warnings', 'imp', 'sys', 'marshal', 'errno', and '_os'
# (a.k.a. 'posix', 'nt' or 'os2').
# Injected attribute is path_sep.


# XXX Could also expose Modules/getpath.c:joinpath()
def _path_join(*args):
    """Replacement for os.path.join so as to remove dependency on os module."""
    return path_sep.join(args)

def _path_exists(path):
    """Replacement for os.path.exists to help remove dependency on 'os'."""
    try:
        _os.stat(path)
    except OSError:
        return False
    else:
        return True


def _path_is_mode_type(path, mode):
    """Test whether the path is the specified mode type."""
    try:
        stat_info = _os.stat(path)
    except OSError:
        return False
    return (stat_info.st_mode & 0o170000) == mode

# XXX Could also expose Modules/getpath.c:isfile()
def _path_isfile(path):
    """Replacement for os.path.isfile."""
    return _path_is_mode_type(path, 0o100000)

# XXX Could also expose Modules/getpath.c:isdir()
def _path_isdir(path):
    """Replacement for os.path.isdir."""
    return _path_is_mode_type(path, 0o040000)

def _path_without_ext(path, ext_type):
    """Replacement for os.path.splitext()[0]."""
    for suffix in suffix_list(ext_type):
        if path.endswith(suffix):
            return path[:-len(suffix)]
    else:
        raise ValueError("path is not of the specified type")

def _path_absolute(path):
    """Replacement for os.path.abspath."""
    try:
        return _os._getfullpathname(path)
    except AttributeError:
        if path.startswith('/'):
            return path
        else:
            return _path_join(_os.getcwd(), path)

def _case_ok(module_name, path, ext=''):
    """Wrapper for imp._case_ok() and its crazy call signature:
        
        Arguments:
        
        - buf
            String containing the path to test.
        - len
            Length of bug minus file extension.
        - name
            Module name.
        
    """
    trimmed_path_len = len(path) - len(ext)
    return imp._case_ok(path, trimmed_path_len, module_name)

def open_(path, flags):
    """Stand-in replacement for open() in case it is not available yet."""
    try:
        # XXX Forcing UTF-8 is fine for a default but there are -*- stanzas to
        # worry about at some point.
        # XXX Opening in UTF-8 prevents the import of heapq and test_coding to
        #  fail at least.
        # XXX Opening in Latin-1 causes test_pep263 and pep_3131 to fail.
        # XXX One possible solution is to read the file in as bytes, do the
        #  universal newline translation, and then look for the -*- stanza to
        #  then do a bytes.decode() call (basically do PEPs 263 and 278).
        # XXX Otherwise consider exposing Python/import.c:parse_source_module().
        return open(path, flags, encoding=(None if 'b' in flags else "utf8"))
    except NameError:
        return DinkyFile(path, flags)

class DinkyFile(object):

    """Dinky replacement of a file object."""

    def __init__(self, path, flags):
        self.writing = 'w' in flags
        self.binary = 'b' in flags
        if self.writing:
            posix_flags = _os.O_WRONLY | _os.O_CREAT
        else:
            posix_flags = _os.O_RDONLY
        self.fd = _os.open(path, posix_flags)

    def read(self):
        if self.writing:
            raise TypeError("file not opened for reading")
        hunk_size = 8 * 1024
        read_out = bytes()
        while True:
            just_read = _os.read(self.fd, hunk_size)
            if not just_read:
                break
            read_out.extend(just_read)
            if len(just_read) < hunk_size:
                break
        if self.binary:
            return read_out
        else:
            # Since codecs requires the ability to import from the encodings
            #  package, bytes.decode() cannot be used.  This forces the
            #  assumption that all files imported before open() is set are
            #  encoded in ASCII.
            return str(read_out)

    def write(self, data):
        if not self.writing or not self.binary:
            raise TypeError("file not opened for writing binary")
        _os.write(self.fd, data)

    def close(self):
        if hasattr(self, 'fd') and self.fd != -1:
            _os.close(self.fd)
            self.fd = -1

    def __del__(self):
        self.close()

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()


class _BuiltinFrozenBaseImporter(object):

    """Base class for meta_path importers for built-in and frozen modules.

    Subclasses must provide the _find and _load methods.

    """

    def find_module(self, fullname, path=None):
        """See if a built-in or frozen module can be imported based on the
        specified name."""
        if self._find(fullname):
            return self
        else:
            return None

    def load_module(self, fullname):
        """Load a built-in or frozen module.

        'imp' code for loading a built-in or frozen module handles the setting
        of a module in sys.modules before initializing the module.  This means
        that we do not need to perform that step as outlined by PEP 302.

        """
        try:
            return sys.modules[fullname]
        except KeyError:
            mod = self._load(fullname)
            if not mod:
                raise ImportError("expected built-in module not loaded")
            return mod


class BuiltinImporter(_BuiltinFrozenBaseImporter):

    """sys.meta_path class for importing built-in modules.
    
    XXX Possible optimization is to bail out in find_module() if 'path' is set
    to a value.
    
    """

    def __init__(self):
        self._find = imp.is_builtin
        self._load = imp.init_builtin


class FrozenImporter(_BuiltinFrozenBaseImporter):

    """sys.meta_path class for importing frozen modules."""

    def __init__(self):
        self._find = imp.is_frozen
        self._load = imp.init_frozen


class ChainedImporter(object):

    """Importer that sequentially calls other importers."""

    def __init__(self, *importers):
        self._importers = importers

    def find_module(self, fullname, path=None):
        for importer in self._importers:
            result = importer.find_module(fullname, path)
            if result:
                return result
        else:
            return None


# XXX Make generic and push fs code into FileImporter?
def chaining_fs_path_hook(*path_hooks):
    """Create a path hook that sequentially asks other path hooks if they can
    handle a sys.path entry, returning a chained importer for those that said
    they could."""
    def chained_fs_path_hook(path_entry):
        """Check which of the associated importers are able to handle the
        filesystem path entry."""
        absolute_path = _path_absolute(path_entry)
        if not _path_isdir(absolute_path):
            raise ImportError("only directories are supported")
        accepted = []
        for path_hook in path_hooks:
            try:
                accepted.append(path_hook(absolute_path))
            except ImportError:
                continue
        if not accepted:
            raise ImportError("no path hooks could handle %s" % path_entry)
        return ChainedImporter(*accepted)
    return chained_fs_path_hook


def check_name(method):
    """Decorator to verify that the module being requested matches the one the
    loader can handle."""
    def inner(self, name, *args, **kwargs):
        if self._name != name:
            raise ImportError("loader cannot handle %s" % name)
        return method(self, name, *args, **kwargs)
    inner.__name__ = method.__name__
    inner.__doc__ = method.__doc__
    inner.__dict__.update(method.__dict__)
    return inner


class _ExtensionFileLoader(object):

    """Provide the ability to load an extension module."""

    def __init__(self, name, path, is_pkg):
        """Initialize the loader, ignoring the is_pkg argument."""
        self._name = name
        self._path = path
        if is_pkg:
            raise ValueError("extension modules cannot be packages")

    @check_name
    def load_module(self, fullname):
        """Load an extension module."""
        assert self._name == fullname
        try:
            module = imp.load_dynamic(fullname, self._path)
            module.__loader__ = self
            return module
        except:
            # If an error occurred, don't leave a partially initialized module.
            if fullname in sys.modules:
                del sys.modules[fullname]
            raise

    @check_name
    def is_package(self, fullname):
        """Return False as an extension module can never be a package."""
        return False

    @check_name
    def get_code(self, fullname):
        """Return None as an extension module cannot create just a code
        object."""
        return None

    @check_name
    def get_source(self, fullname):
        """Return None as extension modules have no source code."""
        return None


def suffix_list(suffix_type):
    """Return a list of suffixes for a specific type of file."""
    return [suffix[0] for suffix in imp.get_suffixes()
            if suffix[2] == suffix_type]


def init_module(loader, code_object, name, path, is_pkg):
    """Return an initialized module.

    If initialization fails and the module did not already exist, then remove
    it from sys.modules to prevent a partially initialized module from being
    left around.  If this action is for a reload (i.e., the module already
    existed), leave the original module state in place.

    """
    module = sys.modules.get(name)
    is_reload = True if module is not None else False
    if not is_reload:
        module = imp.new_module(name)
        sys.modules[name] = module
    else:
        original_values = {}
        modified_attrs = ['__loader__', '__name__', '__file__']
        for attr in modified_attrs:
            try:
                original_values[attr] = getattr(module, attr)
            except AttributeError:
                pass
    module.__loader__ = loader
    module.__name__ = name
    module.__file__ = path
    if is_pkg:
        module.__path__  = [module.__file__.rsplit(path_sep, 1)[0]]
    try:
        exec(code_object, module.__dict__)
    except:
        if not is_reload:
            del sys.modules[name]
        else:
            for attr in modified_attrs:
                if attr in original_values:
                    setattr(module, attr, original_values[attr])
                else:
                    delattr(module, attr)
        raise
    return module


def handle_code(loader, name, source_path, bytecode_path):
    """Return the code object and the location of the code used to create the
    code object in a two-item sequence.
    
    The loader is expected to implement:

    + get_bytecode(name:str) -> str
        Read bytecode.
        Only called if bytecode_path is true.
    + mod_time(name:str) -> int
        Return the last modification time for the source of the specified
        module.
        Only called if both source_path and bytecode_path are true.
    + get_source(name:str) -> str
        Return the source code for the module.
        Only called if source_path is true.
    + write_bytecode(name:str, timestamp:int, data:str) -> bool
        Write out bytecode for the module with the specified timestamp,
        returning a boolean based on whether any actual storage of the bytecode
        was done.
    
    """
    # Request paths instead of just booleans since 'compile' needs it for
    # source.
    if not source_path and not bytecode_path:
        raise ImportError("neither source nor bytecode was specified as "
                            "available")
    source_timestamp = None
    # Try to use bytecode if it is available.
    if bytecode_path:
        magic, pyc_timestamp, bytecode = loader.get_bytecode(name)
        try:
            # Verify that the magic number is valid.
            if imp.get_magic() != magic:
                raise ImportError("bad magic number")
            # Verify that the bytecode is not stale.
            if source_path:
                # Keep in a variable so that if bytecode turns out to be bad
                # then the value can be reused when re-generating bytecode.
                source_timestamp = loader.mod_time(name)
                if pyc_timestamp < source_timestamp:
                    raise ImportError("bytcode is stale")
            # Bytecode seems fine, so try to use it.
            try:
                return marshal.loads(bytecode), bytecode_path
            except ValueError:
                # XXX Is it useful to bail out when the bytecode is bad?  Why
                #  not use the source if possible and issue a warning that the
                #  bytecode was bad?
                # Since bad bytecode halts the import entirely, having the
                #  source code is useless.  Signal this fact by setting
                #  bytecode_path to None.
                bytecode_path = None
                raise ImportError('Non-code object found')
        except ImportError:
            # If the exception is from the bytecode being corrupt, let it
            # propagate.
            if not source_path or bytecode_path is None:
                raise
    # Use the source.
    source = loader.get_source(name)
    code_object = compile(source, source_path, 'exec')
    # Generate bytecode and write it out.
    if source_timestamp is None:  # May have from bytecode verification.
        source_timestamp = loader.mod_time(name)
    data = marshal.dumps(code_object)
    loader.write_bytecode(name, source_timestamp, data)
    return code_object, source_path


class _PyFileLoader(object):
    # XXX Still smart to have this as a separate class?  Or would it work
    # better to integrate with PyFileImporter?  Could cache _is_pkg info.
    # FileImporter can be changed to return self instead of a specific loader
    # call.  Otherwise _base_path can be calculated on the fly without issue if
    # it is known whether a module should be treated as a path or package to
    # minimize stat calls.  Could even go as far as to stat the directory the
    # importer is in to detect changes and then cache all the info about what
    # files were found (if stating directories is platform-dependent).

    """Load a Python source or bytecode file."""

    _handler = handle_code
    _module_init = init_module

    def __init__(self, name, path, is_pkg):
        self._name = name
        self._is_pkg = is_pkg
        # Figure out the base path based on whether it was source or bytecode
        # that was found.
        try:
            self._base_path = _path_without_ext(path, imp.PY_SOURCE)
        except ValueError:
            self._base_path = _path_without_ext(path, imp.PY_COMPILED)

    def _find_path(self, ext_type):
        """Find a path from the base path and the specified extension type that
        exists, returning None if one is not found."""
        for suffix in suffix_list(ext_type):
            path = self._base_path + suffix
            if _path_exists(path):
                return path
        else:
            return None


    def _source_path(self):
        """Return the path to an existing source file for the module, or None
        if one cannot be found."""
        # Not a property so that it is easy to override.
        return self._find_path(imp.PY_SOURCE)

    def _bytecode_path(self):
        """Return the path to a bytecode file, or None if one does not
        exist."""
        # Not a property for easy overriding.
        return self._find_path(imp.PY_COMPILED)

    @check_name
    def load_module(self, fullname):
        """Load a Python source or bytecode file."""
        code_object, path = self._handler(fullname, self._source_path(),
                                            self._bytecode_path())
        return self._module_init(code_object, fullname, path, self._is_pkg)

    @check_name
    def mod_time(self, name):
        """Return the modification time of the source for the specified module.

        Raise ValueError if no source exists or ImportError (like get_source)
        if the loader cannot handle the module.

        """
        source_path = self._source_path()
        if source_path:
            return int(_os.stat(source_path).st_mtime)
        else:
            raise ValueError('no source for %s' % name)

    @check_name
    def get_source(self, fullname):
        """Return the source for the specified module (using universal
        newlines), or None if it is not available.

        Raises ImportError if the loader cannot handle the module.

        """
        source_path = self._source_path()
        if source_path:
            return open_(source_path, 'U').read()
        elif self._bytecode_path():
            return None
        else:
            raise ImportError('no source or bytecode available')

    @check_name
    def get_bytecode(self, name):
        """Return the magic number, timestamp, and the module bytecode for the
        module.

        Raises ImportError (just like get_source) if the laoder cannot handle
        the module.

        """
        try:
            with open_(self._bytecode_path(), 'rb') as bytecode_file:
                data = bytecode_file.read()
            return data[:4], marshal._r_long(data[4:8]), data[8:]
        except AttributeError:
            return None

    @check_name
    def write_bytecode(self, name, timestamp, data):
        """Write out 'data' for the specified module using the specific
        timestamp, returning a boolean
        signifying if the write-out actually occurred.

        Raises ImportError (just like get_source) if the specified module
        cannot be handled by the loader.

        """
        bytecode_path = self._bytecode_path()
        if not bytecode_path:
            bytecode_path = self._base_path + suffix_list(imp.PY_COMPILED)[0]
        try:
            with open_(bytecode_path, 'wb') as bytecode_file:
                bytecode_file.write(imp.get_magic())
                bytecode_file.write(marshal._w_long(timestamp))
                bytecode_file.write(data)
                return True
        except IOError as exc:
            if exc.errno == errno.EACCES:
                return False
            else:
                raise

    def get_data(self, path):
        """Return the data from path as raw bytes."""
        return open_(path, 'rb').read()

    @check_name
    def is_package(self, fullname):
        """Return a boolean based on whether the module is a package.
       
        Raises ImportError (like get_source) if the loader cannot handle the
        package.

        """
        return self._is_pkg

    @check_name
    def get_code(self, fullname):
        """Return a code object for the module.

        Raise ImportError (like get_source) if the load cannot handle the
        specified module.
        
        """
        try:
            return self._handler(fullname, self._source_path(),
                                    self._bytecode_path())[0]
        except ValueError:
            raise ImportError("cannot get the code for %s" % fullname)


class FileImporter(object):

    """Base class for file importers.

    Subclasses are expected to define the following attributes:

    * _suffixes
        Sequence of file suffixes whose order will be followed.
    * _possible_package
        True if importer should check for packages.
    * _loader
        A callable that takes the module name, a file path, and whether
        the path points to a package and returns a loader for the module found
        at that path.

    """

    def __init__(self, path_entry):
        """Initialize an importer for the passed-in sys.path entry (which is
        assumed to have already been verified as an existing directory).

        Can be used as an entry on sys.path_hook.

        """
        self._path_entry = path_entry

    def find_module(self, fullname, path=None):
        tail_module = fullname.rsplit('.', 1)[-1]
        package_directory = None
        if self._possible_package:
            for ext in self._suffixes:
                package_directory = _path_join(self._path_entry, tail_module)
                init_filename = '__init__' + ext
                package_init = _path_join(package_directory, init_filename)
                if (_path_isfile(package_init) and
                        _case_ok(tail_module, package_directory) and
                        _case_ok('__init__', package_init, ext)):
                    return self._loader(fullname, package_init, True)
        for ext in self._suffixes:
            file_name = tail_module + ext
            file_path = _path_join(self._path_entry, file_name)
            if (_path_isfile(file_path) and
                    _case_ok(tail_module, file_path, ext)):
                return self._loader(fullname, file_path, False)
        else:
            # Raise a warning if it matches a directory w/o an __init__ file.
            if (package_directory is not None and
                    _path_isdir(package_directory) and
                    _case_ok(tail_module,
                                _path_join(self._path_entry, tail_module))):
                warnings.warn("Not importing directory %s: missing __init__"
                                    % package_directory,
                                ImportWarning)
            return None


class ExtensionFileImporter(FileImporter):

    """Importer for extension files."""

    _possible_package = False
    _loader = _ExtensionFileLoader

    def __init__(self, path_entry):
        # Assigning to _suffixes here instead of at the class level because
        # imp is not imported at the time of class creation.
        self._suffixes = suffix_list(imp.C_EXTENSION)
        super(ExtensionFileImporter, self).__init__(path_entry)


class PyFileImporter(FileImporter):

    """Importer for source/bytecode files."""

    _possible_package = True
    _loader = _PyFileLoader

    def __init__(self, path_entry):
        # Lack of imp during class creation means _suffixes is set here.
        # Make sure that Python source files are listed first!  Needed for an
        # optimization by the loader.
        self._suffixes = suffix_list(imp.PY_SOURCE)
        self._suffixes += suffix_list(imp.PY_COMPILED)
        super(PyFileImporter, self).__init__(path_entry)


class ImportLockContext(object):

    """Context manager for the import lock."""
    
    def __enter__(self):
        """Acquire the import lock."""
        imp.acquire_lock()
        
    def __exit__(self, exc_type, exc_value, exc_traceback):
        """Release the import lock regardless of any raised exceptions."""
        imp.release_lock()


class Import(object):

    """Class that implements the __import__ interface.
    
    Backwards compatibility is maintained  by extending sys.meta_path
    interally (for handling built-in and frozen modules) and providing a
    default path hooks entry (for extension modules, .py, and .pyc
    files).  Both are controlled during instance initialization.
    
    """

    def __init__(self, default_path_hook=None,
                 extended_meta_path=None):
        """Store a default path hook entry and a sequence to internally extend
        sys.meta_path by (passing in None uses default importers)."""
        if extended_meta_path is None:
            self.extended_meta_path = BuiltinImporter(), FrozenImporter()
        else:
            self.extended_meta_path = extended_meta_path
        self.default_path_hook = default_path_hook
        if self.default_path_hook is None:
            # Create a handler to deal with extension modules, .py, and .pyc
            # files.  Built-in and frozen modules are handled by sys.meta_path
            # entries.
            importers = [ExtensionFileImporter, PyFileImporter]
            self.default_path_hook = chaining_fs_path_hook(*importers)

    def _search_meta_path(self, name, path=None):
        """Check the importers on sys.meta_path for a loader along with the
        extended meta path sequence stored within this instance.
        
        The extended sys.meta_path entries are searched after the entries on
        sys.meta_path.
        
        """
        for entry in (tuple(sys.meta_path) + self.extended_meta_path):
            loader = entry.find_module(name, path)
            if loader:
                return loader
        else:
            raise ImportError("No module named %s" % name)

    def _sys_path_importer(self, path_entry):
        """Return the importer for the specified path, from
        sys.path_importer_cache if possible.
        
        If None is stored in sys.path_importer_cache then use the default path
        hook.
        
        """
        try:
            # See if an importer is cached.
            importer = sys.path_importer_cache[path_entry]
            # If None was returned, use default importer factory.
            if importer is None:
                # XXX Would it break backwards-compatibility to set the importer
                # in sys.path_importer_cache, replacing the None entry and not
                # rely on None being there?
                return self.default_path_hook(path_entry)
            else:
                return importer
        except KeyError:
            # No cached importer found; try to get a new one from
            # sys.path_hooks.
            for importer_factory in sys.path_hooks:
                try:
                    importer = importer_factory(path_entry)
                    # XXX Going to break backwards-compatibility by storing
                    # an instance of the default importer?  None still handled
                    # properly so shouldn't be any different than some other
                    # importer being stored.
                    sys.path_importer_cache[path_entry] = importer
                    return importer
                except ImportError:
                    continue
            else:
                # No importer factory on sys.path_hooks works; use the default
                # importer factory.
                try:
                    importer = self.default_path_hook(path_entry)
                    sys.path_importer_cache[path_entry] = importer
                    return importer
                except ImportError:
                    sys.path_importer_cache[path_entry] = None
                    raise ImportError("no importer found for %s" % path_entry)

    def _search_std_path(self, name, path=None):
        """Check sys.path or 'path' (depending if 'path' is set) for the
        named module and return its loader."""
        if path:
            search_paths = path
        else:
            search_paths = sys.path
        for entry in search_paths:
            try:
                importer = self._sys_path_importer(entry)
            except ImportError:
                continue
            loader = importer.find_module(name)
            if loader:
                return loader
        else:
            raise ImportError("No module named %s" % name)

    def module_from_cache(self, name):
        """Try to return the named module from sys.modules.
        
        Return False if the module is not in the cache. 
        """
        if name in sys.modules:
            return sys.modules[name]
        else:
            return False

    def post_import(self, module):
        """Perform any desired post-import processing on the module."""
        return module
            
    def _import_module(self, name, path=None):
        """Import the specified module with no handling of parent modules.
        
        If None is set for a value in sys.modules (to signify that a relative
        import was attempted and failed) then ImportError is raised.
        
        """
        cached_module = self.module_from_cache(name)
        if cached_module is not False:
            if cached_module is None:
                raise ImportError("relative import redirect")
            else:
                return cached_module
        try:
            # Attempt to find a loader on sys.meta_path.
            loader = self._search_meta_path(name, path)
        except ImportError:
            # sys.meta_path search failed.  Attempt to find a loader on
            # sys.path.  If this fails then module cannot be found.
            loader = self._search_std_path(name, path)
        # A loader was found.  It is the loader's responsibility to have put an
        # entry in sys.modules.
        return self.post_import(loader.load_module(name))

    def _import_full_module(self, name):
        """Import a module along with its parent modules and set into
        sys.modules."""
        # Import the module (importing its parent modules first).
        name_parts = name.split('.')
        current_name_parts = []
        parent_module = None
        path_list = None
        # XXX Any perk to being optimistic and assuming parent modules were
        # imported already, and thus search in the reverse order for the first module
        # to be found?
        for name_part in name_parts:
            current_name_parts.append(name_part)
            # Recreating name every time around the loop is sub-optimal, but
            # does away with base case of a non-dotted name.
            current_name = ".".join(current_name_parts)
            if parent_module:
                try:
                    # XXX Better to use __path__ as found in 'globals' argument
                    # in __call__?  Possibly different if module in sys.modules
                    # resolves to a different one from where the import call
                    # was made.  Not sure if this worth worrying about, though,
                    # since relative imports could easily negate use of
                    # __path__ and sys.modules is totally reasonable to
                    # consider the canonical modules.
                    path_list = parent_module.__path__
                except AttributeError:
                    pass
            module = self._import_module(current_name, path_list)
            if parent_module:
                setattr(parent_module, name_part, module)
            parent_module = module

    def _classic_resolve_name(self, name, caller_name, caller_is_package):
        """Return the absolute name of the module specified in 'name' as based
        on the name of the caller and whether it is a package."""
        if caller_is_package:
            base_name = caller_name
        else:
            if '.' not in caller_name:
                # Importing in a top-level module, so name is already absolute.
                return name
            else:
                base_name = caller_name.rsplit('.', 1)[0]
        return base_name + '.' + name

    def _resolve_name(self, name, caller_name, caller_is_package, level):
        """Return the absolute name of the module specified by 'name' based on
        where the module is being imported and the requested change in dotted
        name level.
        
        Absolute imports always take the form of ``from <name> import ...``.
        This means that the number of leading dots in '<name>' becomes 'level'
        and the rest of '<name>' becomes 'name'.  This leads to the possibility
        that 'name' is the empty string, representing the current package.
        
        """
        if caller_is_package:
            level -= 1
        if caller_name.count('.') < level:
            raise ImportError("attempted relative import beyond top-level "
                                "pacakge")
        base_name = caller_name.rsplit('.', level)[0]
        if name:
            return base_name + '.' + name
        else:
            return base_name
        
    def _return_module(self, absolute_name, relative_name, fromlist):
        """Return the proper module based on what module was requested (and its
        absolute module name), who is requesting it, and whether any specific
        attributes were specified.
        
        The semantics of this method revolve around 'fromlist'.  When it is
        empty, the module up to the first dot is to be returned.  When the
        module being requested is an absolute name this is simple (and
        relative_name is an empty string).  But if the requested module was
        a relative import (as signaled by relative_name having a non-false
        value), then the name up to the first dot in the relative name resolved
        to an absolute name is to be returned.
        
        When fromlist is not empty and the module being imported is a package,
        then the values
        in fromlist need to be checked for.  If a value is not a pre-existing
        attribute a relative import is attempted.  If it fails then suppressed
        the failure silently.
        
        """
        if not fromlist:
            if relative_name:
                absolute_base = absolute_name.rpartition(relative_name)[0]
                relative_head = relative_name.split('.', 1)[0]
                to_return = absolute_base + relative_head
            else:
                to_return = absolute_name.split('.', 1)[0]
            return sys.modules[to_return]
        # When fromlist is not empty, return the actual module specified in
        # the import.
        else:
            module = sys.modules[absolute_name]
            if hasattr(module, '__path__') and hasattr(module, '__name__'):
                # When fromlist has a value and the imported module is a
                # package, then if a name in fromlist is not found as an
                # attribute on module, try a relative import to find it.
                # Failure is fine and the exception is suppressed.
                check_for = list(fromlist)
                if '*' in check_for and hasattr(module, '__all__'):
                    check_for.extend(module.__all__)
                for item in check_for:
                    if item == '*':
                        continue
                    if not hasattr(module, item):
                        resolved_name = self._resolve_name(item, module.__name__,
                                                            True, 1)
                        try:
                            self._import_full_module(resolved_name)
                        except ImportError:
                            pass
            return module

    def __call__(self, name, globals={}, locals={}, fromlist=[], level=-1):
        """Import a module.

        The 'name' argument is the name of the module to be imported (e.g.,
        'foo' in ``import foo`` or ``from foo import ...``).

        'globals' and 'locals' are the global and local namespace dictionaries
        of the module where the import statement appears.  'globals' is used to
        introspect the __path__ and __name__ attributes of the module making
        the call.  'local's is ignored.
        
        'fromlist' lists any specific objects that are to eventually be put
        into the namespace (e.g., ``from for.bar import baz`` would have 'baz'
        in the fromlist, and this includes '*').  An entry of '*' will lead to
        a check for __all__ being defined on the module.  If it is defined then
        the values in __all__ will be checked to make sure that all values are
        attributes on the module, attempting a module import relative to 'name'
        to set that attribute.
        
        When 'name' is a dotted name, there are two different situations to
        consider for the return value.  One is when the fromlist is empty.
        In this situation the import statement imports and returns the name up
        to the first dot.  All subsequent names are imported but set as
        attributes as needed on parent modules.  When fromlist is not empty
        then the module represented by the full dotted name is returned.

        'level' represents how to handle possible relative imports.  If 'level'
        is set to -1 then the module name could be either relative or absolute.
        A value of 0 is for absolute module names., Any positive value
        represents the number of dots listed in the relative import statement
        (e.g. has a value of 2 for ``from .. import foo``).

        """
        if not name and level < 1:
            raise ValueError("Empty module name")
        is_pkg = True if '__path__' in globals else False
        caller_name = globals.get('__name__')
        with ImportLockContext():
            if level and caller_name:
                # Handle the classic style of import: relative first, then
                # absolute.
                if level == -1:
                    relative_name = self._classic_resolve_name(name, caller_name,
                                                                is_pkg)
                    imported_name = relative_name
                    try:
                        # Try a relative import.
                        self._import_full_module(imported_name)
                    except ImportError:
                        # If the relative import fails (or is redirected), try an
                        # absolute import.
                        imported_name = name
                        self._import_full_module(imported_name)
                        # Redirection entry for resolved relative name to instead
                        # redirect to the absolute import.
                        sys.modules[relative_name] = None
                # If using absolute imports with a relative path, only attempt with
                # the fully-resolved module name.
                else:
                    imported_name = self._resolve_name(name, caller_name, is_pkg,
                                                        level)
                    # This call will also handle setting the attribute on the
                    # package.
                    self._import_full_module(imported_name)
            # Absolute module import of a top-level module.
            else:
                imported_name = name
                self._import_full_module(name)
            relative_name = '' if imported_name == name else name
            return self._return_module(imported_name, relative_name, fromlist)

# XXX Eventually replace with a proper __all__ value (i.e., don't expose os
# replacements but do expose _ExtensionFileLoader, etc. for testing).
__all__ = [obj for obj in globals().keys() if not obj.startswith('__')]
