Create Module's import instances

> the indices of imports go before the first index of any definition
> contained in the module itself.
see https://webassembly.github.io/spec/core/syntax/modules.html#imports
768262
function instantiateImports(
  n: Module,
  allocator: Allocator,
  externalElements: Object,
  internals: Object,
  moduleInstance: ModuleInstance
) {
  function getExternalElementOrThrow(key: string, key2: string): any {
    if (
      typeof externalElements[key] === "undefined" ||
      typeof externalElements[key][key2] === "undefined"
    ) {
      throw new CompileError(`Unknown import ${key}.${key2}`);
    }

    return externalElements[key][key2];
  }

  function handleFuncImport(node: ModuleImport, descr: FuncImportDescr) {
    const element = getExternalElementOrThrow(node.module, node.name);

    const params = descr.signature.params != null ? descr.signature.params : [];
    const results =
      descr.signature.results != null ? descr.signature.results : [];

    const externFuncinstance = externvalue.createFuncInstance(
      element,
      // $FlowIgnore
      params,
      results
    );

    const externFuncinstanceAddr = allocator.malloc(
      1 /* sizeof externFuncinstance */
    );
    allocator.set(externFuncinstanceAddr, externFuncinstance);

    moduleInstance.funcaddrs.push(externFuncinstanceAddr);
  }

  function handleGlobalImport(node: ModuleImport, descr: GlobalType) {
    const element = getExternalElementOrThrow(node.module, node.name);

    const externglobalinstance = externvalue.createGlobalInstance(
      new i32(element),
      descr.valtype,
      descr.mutability
    );

    const addr = allocator.malloc(1 /* size of the globalinstance struct */);
    allocator.set(addr, externglobalinstance);

    moduleInstance.globaladdrs.push(addr);
  }

  function handleMemoryImport(node: ModuleImport) {
    const memoryinstance = getExternalElementOrThrow(node.module, node.name);

    const addr = allocator.malloc(1 /* size of the memoryinstance struct */);
    allocator.set(addr, memoryinstance);

    moduleInstance.memaddrs.push(addr);
  }

  function handleTableImport(node: ModuleImport) {
    const tableinstance = getExternalElementOrThrow(node.module, node.name);

    const addr = allocator.malloc(1 /* size of the tableinstance struct */);
    allocator.set(addr, tableinstance);

    moduleInstance.tableaddrs.push(addr);
  }

  traverse(n, {
    ModuleImport({ node }: NodePath<ModuleImport>) {
      switch (node.descr.type) {
        case "FuncImportDescr":
          return handleFuncImport(node, node.descr);
        case "GlobalType":
          return handleGlobalImport(node, node.descr);
        case "Memory":
          return handleMemoryImport(node);
        case "Table":
          return handleTableImport(node);
        default:
          throw new Error("Unsupported import of type: " + node.descr.type);
      }
    }
  });
}
747726
def _prepare_imports(self, dicts):
        
        # all pseudo parent ids we've seen
        pseudo_ids = set()
        # pseudo matches
        pseudo_matches = {}

        # get prepared imports from parent
        prepared = dict(super(OrganizationImporter, self)._prepare_imports(dicts))

        # collect parent pseudo_ids
        for _, data in prepared.items():
            parent_id = data.get('parent_id', None) or ''
            if parent_id.startswith('~'):
                pseudo_ids.add(parent_id)

        # turn pseudo_ids into a tuple of dictionaries
        pseudo_ids = [(ppid, get_pseudo_id(ppid)) for ppid in pseudo_ids]

        # loop over all data again, finding the pseudo ids true json id
        for json_id, data in prepared.items():
            # check if this matches one of our ppids
            for ppid, spec in pseudo_ids:
                match = True
                for k, v in spec.items():
                    if data[k] != v:
                        match = False
                        break
                if match:
                    if ppid in pseudo_matches:
                        raise UnresolvedIdError('multiple matches for pseudo id: ' + ppid)
                    pseudo_matches[ppid] = json_id

        # toposort the nodes so parents are imported first
        network = Network()
        in_network = set()
        import_order = []

        for json_id, data in prepared.items():
            parent_id = data.get('parent_id', None)

            # resolve pseudo_ids to their json id before building the network
            if parent_id in pseudo_matches:
                parent_id = pseudo_matches[parent_id]

            network.add_node(json_id)
            if parent_id:
                # Right. There's an import dep. We need to add the edge from
                # the parent to the current node, so that we import the parent
                # before the current node.
                network.add_edge(parent_id, json_id)

        # resolve the sorted import order
        for jid in network.sort():
            import_order.append((jid, prepared[jid]))
            in_network.add(jid)

        # ensure all data made it into network (paranoid check, should never fail)
        if in_network != set(prepared.keys()):    # pragma: no cover
            raise PupaInternalError("import is missing nodes in network set")

        return import_order
615569
def generate_import_from(module_, names):
        
        regular_names = [n for n in names if "::" not in n]
        as_names = [n for n in names if "::" in n]

        line = ""
        if len(regular_names) > 0:
            slots = {"m": module_, "n": ", ".join(sorted(regular_names))}
            line = "from %(m)s import %(n)s" % slots
            if len(line) > LINE_LENGTH_LIMIT:
                slots["n"] = INDENT + (",\n" + INDENT).join(sorted(regular_names)) + ","
                line = "from %(m)s import (\n%(n)s\n)" % slots
            if len(as_names) > 0:
                line += "\n"

        for as_name in as_names:
            a, n = as_name.split("::")
            line += "from %(m)s import %(n)s as %(a)s" % {"m": module_, "n": n, "a": a}
        return line
171247
def import_assist(self, starting):
        
        # XXX: breaking if gave up! use generators
        result = []
        for module in self.names:
            for global_name in self.names[module]:
                if global_name.startswith(starting):
                    result.append((global_name, module))
        return result
1183755
def instantiate_modules
      mods = Array(modules)
      mods = load!(mods) if callback?(:load)
      Array(mods).map do |klass|
        init!(klass) || klass.new(fetchable)
      end
    end
79545
def __get_from_imports(import_tuples):
    
    from_imports = [(tup[0], tup[1]) for tup in import_tuples
                    if tup[1] is not None and len(tup[1]) > 0]
    return from_imports
280033
def import_module(modulename):
    
    module = None
    try:
        module = importlib.import_module(modulename)
    except ImportError:
        # If importing fails we see if the modulename has dots in it, split the name.
        if "." in modulename:
            modules = modulename.split(".")
            package = ".".join(modules[1:len(modules)])
            # Might raise an ImportError again. If so, we really failed to import the module.
            module = importlib.import_module(package)
        else:
            # No dots, really unable to import the module. Raise.
            raise
    return module
774107
function buildExportInitializationStatements(
  programPath: NodePath,
  metadata: ModuleMetadata,
  loose: boolean = false,
) {
  const initStatements = [];

  const exportNames = [];
  for (const [localName, data] of metadata.local) {
    if (data.kind === "import") {
      // No-open since these are explicitly set with the "reexports" block.
    } else if (data.kind === "hoisted") {
      initStatements.push(
        buildInitStatement(metadata, data.names, t.identifier(localName)),
      );
    } else {
      exportNames.push(...data.names);
    }
  }

  for (const data of metadata.source.values()) {
    if (!loose) {
      initStatements.push(...buildReexportsFromMeta(metadata, data, loose));
    }
    for (const exportName of data.reexportNamespace) {
      exportNames.push(exportName);
    }
  }

  initStatements.push(
    ...chunk(exportNames, 100).map(members => {
      return buildInitStatement(
        metadata,
        members,
        programPath.scope.buildUndefinedNode(),
      );
    }),
  );

  return initStatements;
}
113624
def init(name, subnames, dest, skeleton, description, project_type, skip_core):
    """"""
    dest = dest or CUR_DIR
    skeleton = join(skeleton or SKEL_PATH, project_type)
    project = join(dest, name)
    script = join(project, name + '.py')
    core = join(project, name)
    if project_type == 'standalone':
        renames = [
            (join(project, 'project.py'), script),
            (join(project, 'project'), core)]
        copy_skeleton(
            name, skeleton, project, renames=renames, description=description,
            ignore=False)
    else:
        renames = [
            (join(project, 'project.py'), script),
            (join(project, 'project'), core)]
        exclude_dirs = ['submodule'] + (['project'] if skip_core else [])
        copy_skeleton(
            name, skeleton, project, renames=renames, description=description,
            exclude_dirs=exclude_dirs, ignore=True)
        for subname in subnames:
            renames = [
                (join(project, 'submodule'), join(project, subname))
            ]
            copy_skeleton(
                subname, skeleton, project, renames=renames,
                description=description, ignore=True,
                exclude_dirs=['project'], exclude_files=['project.py'])
    return 0, "\n{}\n".format(project)
927104
def imports():
    
    from .core.import_hooks import ExtensionImporter
    importer = ExtensionImporter()
    sys.meta_path.append(importer)
    yield
    sys.meta_path.remove(importer)
582482
def enumerate_imports(tokens):
    
    imported_modules = []
    import_line = False
    from_import = False
    for index, tok in enumerate(tokens):
        token_type = tok[0]
        token_string = tok[1]
        if token_type == tokenize.NEWLINE:
            import_line = False
            from_import = False
        elif token_string == "import":
            import_line = True
        elif token_string == "from":
            from_import = True
        elif import_line:
            if token_type == tokenize.NAME and tokens[index+1][1] != 'as':
                if not from_import:
                    if token_string not in reserved_words:
                        if token_string not in imported_modules:
                            imported_modules.append(token_string)
    return imported_modules
645512
def get_module_imports_on_top_of_file(source, import_line_index):
    
    def is_string_literal(line):
        if line[0] in 'uUbB':
            line = line[1:]
        if line and line[0] in 'rR':
            line = line[1:]
        return line and (line[0] == '"' or line[0] == "'")

    def is_future_import(line):
        nodes = ast.parse(line)
        for n in nodes.body:
            if isinstance(n, ast.ImportFrom) and n.module == '__future__':
                return True
        return False

    allowed_try_keywords = ('try', 'except', 'else', 'finally')
    in_docstring = False
    docstring_kind = '"""'
    for cnt, line in enumerate(source):
        if not in_docstring:
            m = DOCSTRING_START_REGEX.match(line.lstrip())
            if m is not None:
                in_docstring = True
                docstring_kind = m.group('kind')
                remain = line[m.end(): m.endpos].rstrip()
                if remain[-3:] == docstring_kind:  # one line doc
                    in_docstring = False
                continue
        if in_docstring:
            if line.rstrip()[-3:] == docstring_kind:
                in_docstring = False
            continue

        if not line.rstrip():
            continue
        elif line.startswith('#'):
            continue

        if line.startswith('import ') or line.startswith('from '):
            if cnt == import_line_index or is_future_import(line):
                continue
            return cnt
        elif pycodestyle.DUNDER_REGEX.match(line):
            continue
        elif any(line.startswith(kw) for kw in allowed_try_keywords):
            continue
        elif is_string_literal(line):
            return cnt
        else:
            return cnt
    return 0
333823
def _init():
    """"""
    import importlib
    import os
    import re

    filenames = os.listdir(os.path.dirname(__file__))

    module_names = set()
    for filename in filenames:
        match = re.match(r'^(?P<name>[A-Z_a-z]\w*)\.py[co]?$', filename)
        if match:
            module_names.add(match.group('name'))

    for module_name in module_names:
        try:
            module = importlib.import_module('.' + module_name, __name__)
        except ImportError:
            continue

        for name, member in module.__dict__.items():
            if not isinstance(member, type):
                # skip non-new-style classes
                continue
            if not issubclass(member, Engine):
                # skip non-subclasses of Engine
                continue
            if member is Engine:
                # skip "abstract" class Engine
                continue

            try:
                handle = member.handle
            except AttributeError:
                continue

            engines[handle] = member
813900
function makeModule(index) {

		var stored, src, srcPath, relpath;

		// Prepare module
		var module  = new Module({
			 uid:    index
			,req:    []
			,path:   index
			,relpath: null
			,isNodeModule: false
			,isAsyncModule: arequirePath === index
			,arequirePath:  arequirePath
			,index:  index
		});

		if(~module.path.indexOf('/node_modules/')) module.isNodeModule = true;

		relpath = path.relative(process.cwd(), module.path);
		relpath = !/^\./.test(relpath) ? './' + relpath : relpath;
		module.relpath = relpath;

		debug('makeModule for %s', relpath);

		// Check for stored version of this path
		stored = _.find(modules, function(p) {
			return module.path === p.path;
		});
		if(stored) {
			debug('allready stored : return (absolute path match)');
			return stored;
		}

		// Read source
		src           = fs.readFileSync(module.path, 'utf8');
		module.mtime  = fs.statSync(module.path).mtime;
		module.uid    = getUID({src: src, path:module.path, options: options});

		// Check for stored version with same uid
		stored = _.find(modules, function(p) {
			return module.uid  === p.uid;
		});
		if(stored) {
			debug('allready stored : return (md5 hash match)');
			return stored;
		}

		// Save module
		modules.push(module);

		// Do not parse ?
		module.notparsed = _.find(noparse, function(np) {
			if(np instanceof RegExp) {
				return np.test(module.path);
			} else if ('string'   == typeof np) {
				return minimatch(module.path, np);
			} else if ('function' == typeof np) {
				return np(module.path, module);
			} else {
				return false;
			}
		});

		// Parse
		if(module.notparsed) {
			debug('  no parse');
		} else {
			debug('  run parse');
			src = parse(src, module, makeModule, options);
		}

		// Store the module source :
		module.source = src;


		// Return the module object

		debug('end %s', relpath);
		return module;
	}
1346189
def with_indices(*args):
    '''
    
    '''
    def decorator(cls):
        for c in cls.__bases__:
            if hasattr(c, '_indicesNames'):
                cls._classnameIndex = c._classnameIndex + 1
                for i in range(0, cls._classnameIndex):
                    setattr(cls, '_classname' + str(i), getattr(c, '_classname' + str(i)))
                setattr(cls, '_classname' + str(cls._classnameIndex), cls._getTypename())
                cls._indicesNames = c._indicesNames + ('_classname' + str(cls._classnameIndex),) + args
                cls._generateTemplate()
                return cls
        cls._classnameIndex = -1
        cls._indicesNames = args
        cls._generateTemplate()
        return cls
    return decorator
271596
def my_import(name):
    
    module, attr = name.rsplit('.', 1)
    mod = __import__(module, fromlist=[attr])
    klass = getattr(mod, attr)
    return klass()
486909
def _initAddons(cls, recurse=True):
        
        for addon_module in cls.addonModules(recurse):
            projex.importmodules(addon_module)