Build a dependency tree of ASTs given a root module
499418
function buildTree(index, api) {
  const modules = {};

  const dependency = (module, parent) => {
    const filepath = api.resolve(module, parent);
    if (modules[filepath] != null) {
      return modules[filepath];
    }

    const src = api.getFileContents(module, parent, "utf8");
    const basic = api.parser(src);
    const [nestedImports, hasMemory] = parseImports(basic, api);

    const deps = {};

    Object.keys(nestedImports).forEach(mod => {
      if (mod.indexOf(".") === 0) {
        const dep = dependency(mod, filepath);
        deps[mod] = dep;
      }
    });

    const patched = inferImportTypes(basic, deps, api);
    const ast = api.semantics(patched);

    api.validate(ast, {
      lines: src.split("\n"),
      filename: module.split("/").pop(),
    });

    const result = {
      ast,
      deps,
      filepath,
      hasMemory,
    };
    modules[filepath] = result;

    return result;
  };

  const root = dependency(index, null);

  return {
    root,
    modules,
  };
}
1032460
def futurize_module(module_path, show_diff, write_update):
    """"""
    logging.info('Futurizing module... path="{}"'.format(module_path))
    ast_tree = back_to_the_futurize(module_path)
    return d1_dev.util.update_module_file_ast(
        ast_tree, module_path, show_diff, write_update
    )
681766
function Dependencies(module, dependencies) {
        "use strict";
    
        var modules = {};
        Object.defineProperty(this, 'modules', {
            'get': function () {
                return modules;
            }
        });
    
        this.set = function (value) {
    
            if (dependencies) {
                console.error('Module dependencies can only be set once')
                return;
            }
            dependencies = value;
            load();
    
        };
    
        var ready;
        Object.defineProperty(this, 'loaded', {
            'get': function () {
                return !!ready;
            }
        });
    
        var callbacks = [];
    
        function done() {
    
            ready = true;
            for (var i in callbacks) {
                callbacks[i](modules);
            }
            callbacks = [];
    
        }
    
        this.done = function (callback) {
    
            if (ready) {
                callback(modules);
                return;
            }
            callbacks.push(callback);
    
        };
    
        var coordinate = new Coordinate(
            'controls',
            'require',
            'react',
            done);
    
        function getResourcePath(resource) {
    
            if (resource.substr(0, 12) === 'application/') {
                return 'application/' + resource.substr(12);
            }
    
            if (resource.substr(0, 10) !== 'libraries/') {
                return resource;
            }
    
            var type;
    
            // Extract the type of the resource to get the moduleID
            var moduleID = (function (resource) {
    
                resource = resource.split('/');
                type = resource.pop();
                return resource.join('/');
    
            })(resource);
    
            var multilanguage = beyond.modules.multilanguage.get(moduleID);
            if (multilanguage && multilanguage.indexOf(type) !== -1) {
                return resource + '/' + beyond.params.language;
            }
            else {
                return resource;
            }
    
        }
    
        function load() {
    
            var mods = [];
    
            var dependency;
            for (var resource in dependencies.require) {
                mods.push(getResourcePath(resource));
            }
    
            // Wait for react to be ready if react is on the dependencies list
            if (mods.indexOf('react') !== -1) {
                module.react.done(coordinate.react);
            }
            else {
                coordinate.done('react');
            }
    
            if (mods.length) {
    
                require(mods, function () {
    
                    var args = [].slice.call(arguments);
    
                    var i = 0;
                    for (dependency in dependencies.require) {
    
                        var name = dependencies.require[dependency];
                        modules[name] = args[i];
                        i++;
    
                    }
    
                    coordinate.done('require');
    
                });
    
            }
            else {
                coordinate.done('require');
            }
    
            if (dependencies.controls instanceof Array && dependencies.controls.length) {
                beyond.controls.import(dependencies.controls, coordinate.controls);
            }
            else {
                coordinate.done('controls');
            }
    
        }
    
        if (dependencies) load();
    
    }
1299684
def _load_greedy(self, module_name, dependencies, recursive):
        """"""
        found = module_name in self.modules
        allmodules = list(self._pathfiles.keys())
        i = 0

        while not found and i < len(allmodules):
            current = allmodules[i]
            if not current in self._modulefiles:
                #We haven't tried to parse this file yet
                self.parse(self._pathfiles[current], dependencies and recursive)                
                found = module_name in self.modules
            i += 1
683391
function(rootNode, includeRoot) {
			var arr = null,
				out = [],
				classList = [],
				items,
				x,
				i,
				y,
				key;


			// build an array of v1 root names
			for(key in modules.maps) {
				if (modules.maps.hasOwnProperty(key)) {
					classList.push(modules.maps[key].root);
				}
			}

			// get all elements that have a class attribute
			includeRoot = (includeRoot) ? includeRoot : false;
			if(includeRoot && rootNode.parentNode) {
				arr = modules.domUtils.getNodesByAttribute(rootNode.parentNode, 'class');
			} else {
				arr = modules.domUtils.getNodesByAttribute(rootNode, 'class');
			}

			// loop elements that have a class attribute
			x = 0;
			i = arr.length;
			while(x < i) {

				items = modules.domUtils.getAttributeList(arr[x], 'class');

				// loop classes on an element
				y = items.length;
				while(y--) {
					// match v1 root names
					if(classList.indexOf(items[y]) > -1) {
						out.push(arr[x]);
						break;
					}

					// match v2 root name prefix
					if(modules.utils.startWith(items[y], 'h-')) {
						out.push(arr[x]);
						break;
					}
				}

				x++;
			}
			return out;
		}
502312
function resolvePath (moduleName, relativePath)
{
  if (! moduleName) {
    return null;
  }

  if (! relativePath) {
    return null;
  }

  const mainPath = require.resolve(moduleName);
  if (! mainPath) {
    return null;
  }

  const rootLocations = [];
  const dirs = mainPath.split(path.sep);
  let lastSegment = dirs.pop();
  while (lastSegment) {
    const location = dirs.concat(['package.json']).join(path.sep);
    rootLocations.push(location);
    lastSegment = dirs.pop();
  }

  for(const location of rootLocations) {
    if (fs.existsSync(location)) {
      const cli = path.resolve(path.dirname(location), relativePath);
      if (fs.existsSync(cli)) {
        return cli;
      }
    }
  }

  return null;
}
899887
function assemble(tree, options, api) {
  return Object.entries(tree.modules).reduce((opcodes, [filepath, mod]) => {
    // There are two cases when we should generate a DATA section for module,
    // it has statics OR it imports a memory. As then it needs to share the
    // same information about the memory layout as the rest of the application.
    let statics = mod.ast.meta.AST_METADATA.statics;
    if (Object.keys(statics).length > 0 || mod.hasMemory) {
      // Use global statics object
      statics = options.linker.statics;
    }

    const code = api.generator(
      mod.ast,
      Object.assign({}, options, { filename: mod.filepath.split('/').slice(-1)[0], linker: { statics } })
    );
    const wasm = api.emitter(code, options).buffer();

    return Object.assign({}, opcodes, {
      [filepath]: wasm,
    });
  }, {});
}
1138075
function parseDependenciesList (root, string) {
  return string.split(/\s+/).reduce(function (accumulator, dependency) {
    if (dependency.length > 0) {
      var absolutePath = path.resolve(root, defaultFileExtension(dependency))
      accumulator.push(absolutePath)
    }
    return accumulator
  }, [])
}
439703
def _module_iterator(root, recursive=True):
    """"""
    yield root

    stack = collections.deque((root,))
    while stack:
        package = stack.popleft()
        # The '__path__' attribute of a package might return a list of paths if
        # the package is referenced as a namespace.
        paths = getattr(package, '__path__', [])
        for path in paths:
            modules = pkgutil.iter_modules([path])
            for finder, name, is_package in modules:
                module_name = '%s.%s' % (package.__name__, name)
                module = sys.modules.get(module_name, None)
                if module is None:
                    # Import the module through the finder to support package
                    # namespaces.
                    module = _load_module(finder, module_name)

                if is_package:
                    if recursive:
                        stack.append(module)
                        yield module
                else:
                    yield module
453093
def node_branch(self, astr_node, abranch):
            
            self.dict_branch[astr_node].node_dictBranch(abranch.dict_branch)
574674
function build(importsObj, tree) {
  const modules = {};

  const instantiate = filepath => {
    if (modules[filepath] != null) {
      return modules[filepath];
    }

    const mod = tree.modules[filepath];
    const promise = Promise.all(
      Object.entries(mod.deps).map(([key, dep]) => {
        return instantiate(dep.filepath).then(result => [key, result]);
      })
    )
      .then(importsMap => {
        const imports = importsMap.reduce((acc, [key, module]) => {
          acc[key] = module.instance.exports;
          return acc;
        }, {});

        return WebAssembly.instantiate(
          tree.opcodes[filepath],
          Object.assign({}, imports, importsObj)
        );
      })
      .catch(e => {
        // TODO: do some logging here
        throw e;
      });

    modules[filepath] = promise;

    return promise;
  };

  modules[tree.root.filepath] = instantiate(tree.root.filepath);

  return modules[tree.root.filepath];
}
887720
def build_module(name, doc=None):
    """"""
    node = nodes.Module(name, doc, pure_python=False)
    node.package = False
    node.parent = None
    return node
1144178
def load_dependency(self, module_name, dependencies, recursive, greedy, ismapping = False):
        """"""
        key = module_name.lower()
        if key not in self.modules:
            if key == "fortpy":
                #Manually specify the correct path to the fortpy.f90 that shipped with
                #the distribution
                from fortpy.utility import get_fortpy_templates_dir
                from os import path
                fpy_path = path.join(get_fortpy_templates_dir(), "fortpy.f90")
                self.parse(fpy_path, False, False)
                return
            
            fkey = key + ".f90"
            if fkey in self._pathfiles:
                self.parse(self._pathfiles[fkey], dependencies, recursive)
            elif greedy:
                #The default naming doesn't match for this module
                #we will load all modules until we find the right
                #one
                self._load_greedy(key, dependencies, recursive)
            elif key in self.mappings and self.mappings[key] in self._pathfiles:
                #See if they have a mapping specified to a code file for this module name.
                if self.verbose:
                    msg.info("MAPPING: using {} as the file".format(self.mappings[key]) + 
                             " name for module {}".format(key))
                self.parse(self._pathfiles[self.mappings[key]], dependencies, recursive)
            elif key not in ["mkl_vsl_type", "mkl_vsl", "iso_c_binding"]:
                #The parsing can't continue without the necessary dependency modules.
                msg.err(("could not find module {}. Enable greedy search or"
                       " add a module filename mapping.".format(key)))
                if self.austere:
                    exit(1)
663678
def export_tree(lookup, tree, path):
    
    FILE_PERM = S_IRWXU | S_IRWXG | S_IRWXO

    for name, mode, hexsha in tree.iteritems():
        dest = os.path.join(path, name)

        if S_ISGITLINK(mode):
            log.error('Ignored submodule {}; submodules are not yet supported.'
                      .format(name))
            # raise ValueError('Does not support submodules')
        elif S_ISDIR(mode):
            os.mkdir(dest)
            os.chmod(dest, 0o0755)
            export_tree(lookup, lookup(hexsha), dest)
        elif S_ISLNK(mode):
            os.symlink(lookup(hexsha).data, dest)
        elif S_ISREG(mode):
            with open(dest, 'wb') as out:
                for chunk in lookup(hexsha).chunked:
                    out.write(chunk)
            os.chmod(dest, mode & FILE_PERM)
        else:
            raise ValueError('Cannot deal with mode of {:o} from {}'.format(
                mode, name))
1265140
function _buildDependencyTreeOf(node) {
		var requireStatements = getRequireStatements(getCode(node.path))
		if (requireStatements.length == 0) {
			return leaves.push(node)
		}
		each(requireStatements, function(requireStatement) {
			var childNode = []
			childNode.path = resolve.requireStatement(requireStatement, node.path)
			childNode.parent = node
			node.push(childNode)
			_buildDependencyTreeOf(childNode)
		})
		node.waitingForNumChildren = node.length
	}
1080868
def _build_all_dependencies(self):
        '''
        
        '''
        ret = {}
        for model, schema in six.iteritems(self._models()):
            dep_list = self._build_dependent_model_list(schema)
            ret[model] = dep_list
        return ret
1330094
function mapByDepth(rootPackage) {
    var depth = 0
      , allDeps = {}
      , superDepsList = {}
      ;

    function traverseDeps(childPackage) {
      depth += 1;

      childPackage.dependencyTree = childPackage.dependencyTree || {};
      Object.keys(childPackage.dependencyTree).forEach(function (depName) {
        var childDeps = (childPackage.dependencyTree[depName] || {}) || {}
          ;

        if (superDepsList[depName]) {
          // a dependency can't (meaning shouldn't) have a path in which it depends on itself
          // this kind of resolution isn't as important as it once was
          // since the modules can be loaded out-of-order
          return;
        }

        superDepsList[depName] = true;

        allDeps[depth] = allDeps[depth] || [];
        allDeps[depth].push(depName);

        if (childDeps) {
          traverseDeps(childDeps);
        }

        superDepsList[depName] = false;
      });

      depth -= 1;
    }

    traverseDeps(rootPackage);

    return allDeps;
  }