// NewModuleTree returns a new ModuleTreeNode that represents the root
// of the module tree populated with the given modules.
325910
func NewModuleTree(mods map[string]*Module) *ModuleTreeNode {
	root := &ModuleTreeNode{
		Children: map[Value]*ModuleTreeNode{},
	}
	for _, m := range mods {
		node := root
		for i, x := range m.Package.Path {
			c, ok := node.Children[x.Value]
			if !ok {
				var hide bool
				if i == 1 && x.Value.Compare(SystemDocumentKey) == 0 {
					hide = true
				}
				c = &ModuleTreeNode{
					Key:      x.Value,
					Children: map[Value]*ModuleTreeNode{},
					Hide:     hide,
				}
				node.Children[x.Value] = c
			}
			node = c
		}
		node.Modules = append(node.Modules, m)
	}
	return root
}
116396
func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
	// If no or partial configurations were specified, use defaults
	if config == nil {
		config = NewNodeConfig()
	}
	if config.MaxPeers == 0 {
		config.MaxPeers = defaultNodeConfig.MaxPeers
	}
	if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
		config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
	}

	if config.PprofAddress != "" {
		debug.StartPProf(config.PprofAddress)
	}

	// Create the empty networking stack
	nodeConf := &node.Config{
		Name:        clientIdentifier,
		Version:     params.VersionWithMeta,
		DataDir:     datadir,
		KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
		P2P: p2p.Config{
			NoDiscovery:      true,
			DiscoveryV5:      true,
			BootstrapNodesV5: config.BootstrapNodes.nodes,
			ListenAddr:       ":0",
			NAT:              nat.Any(),
			MaxPeers:         config.MaxPeers,
		},
	}

	rawStack, err := node.New(nodeConf)
	if err != nil {
		return nil, err
	}

	debug.Memsize.Add("node", rawStack)

	var genesis *core.Genesis
	if config.EthereumGenesis != "" {
		// Parse the user supplied genesis spec if not mainnet
		genesis = new(core.Genesis)
		if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
			return nil, fmt.Errorf("invalid genesis spec: %v", err)
		}
		// If we have the testnet, hard code the chain configs too
		if config.EthereumGenesis == TestnetGenesis() {
			genesis.Config = params.TestnetChainConfig
			if config.EthereumNetworkID == 1 {
				config.EthereumNetworkID = 3
			}
		}
	}
	// Register the Ethereum protocol if requested
	if config.EthereumEnabled {
		ethConf := eth.DefaultConfig
		ethConf.Genesis = genesis
		ethConf.SyncMode = downloader.LightSync
		ethConf.NetworkId = uint64(config.EthereumNetworkID)
		ethConf.DatabaseCache = config.EthereumDatabaseCache
		if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
			return les.New(ctx, &ethConf)
		}); err != nil {
			return nil, fmt.Errorf("ethereum init: %v", err)
		}
		// If netstats reporting is requested, do it
		if config.EthereumNetStats != "" {
			if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
				var lesServ *les.LightEthereum
				ctx.Service(&lesServ)

				return ethstats.New(config.EthereumNetStats, nil, lesServ)
			}); err != nil {
				return nil, fmt.Errorf("netstats init: %v", err)
			}
		}
	}
	// Register the Whisper protocol if requested
	if config.WhisperEnabled {
		if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) {
			return whisper.New(&whisper.DefaultConfig), nil
		}); err != nil {
			return nil, fmt.Errorf("whisper init: %v", err)
		}
	}
	return &Node{rawStack}, nil
}
1299327
func newNode(index int, parent *node, hasher hash.Hash) *node {
	return &node{
		parent: parent,
		isLeft: index%2 == 0,
		hasher: hasher,
	}
}
41145
func NewGraph(modules map[string]*Module, list func(Ref) []*Rule) *Graph {

	graph := &Graph{
		adj:    map[util.T]map[util.T]struct{}{},
		nodes:  map[util.T]struct{}{},
		sorted: nil,
	}

	// Create visitor to walk a rule AST and add edges to the rule graph for
	// each dependency.
	vis := func(a *Rule) Visitor {
		stop := false
		return NewGenericVisitor(func(x interface{}) bool {
			switch x := x.(type) {
			case Ref:
				for _, b := range list(x.GroundPrefix()) {
					for node := b; node != nil; node = node.Else {
						graph.addDependency(a, node)
					}
				}
			case *Rule:
				if stop {
					// Do not recurse into else clauses (which will be handled
					// by the outer visitor.)
					return true
				}
				stop = true
			}
			return false
		})
	}

	// Walk over all rules, add them to graph, and build adjencency lists.
	for _, module := range modules {
		WalkRules(module, func(a *Rule) bool {
			graph.addNode(a)
			Walk(vis(a), a)
			return false
		})
	}

	return graph
}
1294033
func (t *Tree) Modules() []*Module {
	result := make([]*Module, len(t.config.Modules))
	for i, m := range t.config.Modules {
		result[i] = &Module{
			Name:      m.Name,
			Version:   m.Version,
			Source:    m.Source,
			Providers: m.Providers,
		}
	}

	return result
}
486959
func New(dims, maxEntries int) *RTree {
	if dims <= 0 {
		panic("invalid dimensions")
	}

	tr := &RTree{}
	tr.dims = dims
	tr.maxEntries = int(math.Max(4, float64(maxEntries)))
	tr.minEntries = int(math.Max(2, math.Ceil(float64(tr.maxEntries)*0.4)))
	tr.data = tr.createNode(nil)
	return tr
}
1273450
func (t *importTree) ConfigTree() (*configTree, error) {
	config, err := t.Raw.Config()
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("Error loading %s: {{err}}", t.Path), err)
	}

	// Build our result
	result := &configTree{
		Path:   t.Path,
		Config: config,
	}

	// Build the config trees for the children
	result.Children = make([]*configTree, len(t.Children))
	for i, ct := range t.Children {
		t, err := ct.ConfigTree()
		if err != nil {
			return nil, err
		}

		result.Children[i] = t
	}

	return result, nil
}
83842
func NewModulateResultError(message string, values ...interface{}) ModulateResultError {
	return ModulateResultError{
		message: fmt.Sprintf(message, values...),
	}
}
307374
func newRadixTreeString(prefixStrings ...string) *radixTree {
	prefixes := make([][]byte, len(prefixStrings))
	for i, prefix := range prefixStrings {
		prefixes[i] = []byte(prefix)
	}
	return newRadixTree(prefixes...)
}
366092
func NewFromRoots(roots []string, opts *RootsOptions) (*Parser, error) {
	if opts == nil {
		opts = &RootsOptions{}
	}

	if len(roots) == 0 {
		pwd, _ := os.Getwd()
		roots = append(roots, pwd)
	}
	p := New()
	plog.Debug(p, "NewFromRoots", "roots", roots, "options", opts)
	callback := func(path string, de *godirwalk.Dirent) error {
		if IsProspect(path, opts.Ignores...) {
			if de.IsDir() {
				return nil
			}
			roots = append(roots, path)
			return nil
		}
		if de.IsDir() {
			return filepath.SkipDir
		}
		return nil
	}
	wopts := &godirwalk.Options{
		FollowSymbolicLinks: true,
		Callback:            callback,
	}
	for _, root := range roots {
		plog.Debug(p, "NewFromRoots", "walking", root)
		err := godirwalk.Walk(root, wopts)
		if err != nil {
			return p, err
		}
	}

	dd := map[string]string{}
	fd := &finder{id: time.Now()}
	for _, r := range roots {
		var names []string
		if opts.IgnoreImports {
			names, _ = fd.findAllGoFiles(r)
		} else {
			names, _ = fd.findAllGoFilesImports(r)
		}
		for _, n := range names {
			if IsProspect(n) {
				plog.Debug(p, "NewFromRoots", "mapping", n)
				dd[n] = n
			}
		}
	}
	for path := range dd {
		plog.Debug(p, "NewFromRoots", "reading file", path)
		b, err := ioutil.ReadFile(path)
		if err != nil {
			return nil, err
		}
		p.Prospects = append(p.Prospects, NewFile(path, bytes.NewReader(b)))
	}
	plog.Debug(p, "NewFromRoots", "found prospects", len(p.Prospects))
	return p, nil
}
1203659
func (m *ModulesManager) findModules(expectedNames ...string) (bool, []string) {
	return set.SliceSubsetOf(expectedNames, m.modulesList)
}
815425
func generateModule(m *compile.Module, i thriftPackageImporter, builder *generateServiceBuilder, o *Options) (map[string][]byte, error) {
	// packageRelPath is the path relative to outputDir into which we'll be
	// writing the package for this Thrift file. For $thriftRoot/foo/bar.thrift,
	// packageRelPath is foo/bar, and packageDir is $outputDir/foo/bar. All
	// files for bar.thrift will be written to the $outputDir/foo/bar/ tree. The
	// package will be importable via $importPrefix/foo/bar.
	packageRelPath, err := i.RelativePackage(m.ThriftPath)
	if err != nil {
		return nil, err
	}

	// TODO(abg): Prefer top-level package name from `namespace go` directive.
	packageName := filepath.Base(packageRelPath)

	// importPath is the full import path for the top-level package generated
	// for this Thrift file.
	importPath, err := i.Package(m.ThriftPath)
	if err != nil {
		return nil, err
	}

	// Mapping of file names relative to packageRelPath to their contents.
	// Note that we need to return a mapping relative to o.OutputDir so we
	// will prepend $packageRelPath/ to all these paths.
	files := make(map[string][]byte)

	gopts := &GeneratorOptions{
		Importer:    i,
		ImportPath:  importPath,
		PackageName: packageName,
		NoZap:       o.NoZap,
	}
	g := NewGenerator(gopts)

	if len(m.Constants) > 0 {
		for _, constantName := range sortStringKeys(m.Constants) {
			if err := Constant(g, m.Constants[constantName]); err != nil {
				return nil, err
			}
		}

		buff := new(bytes.Buffer)
		if err := g.Write(buff, nil /* fset */); err != nil {
			return nil, fmt.Errorf(
				"could not generate constants for %q: %v", m.ThriftPath, err)
		}

		// TODO(abg): Verify no file collisions
		if !o.NoConstants {
			files["constants.go"] = buff.Bytes()
		}
	}

	if len(m.Types) > 0 {
		for _, typeName := range sortStringKeys(m.Types) {
			if err := TypeDefinition(g, m.Types[typeName]); err != nil {
				return nil, err
			}
		}

		buff := new(bytes.Buffer)
		if err := g.Write(buff, nil /* fset */); err != nil {
			return nil, fmt.Errorf(
				"could not generate types for %q: %v", m.ThriftPath, err)
		}

		// TODO(abg): Verify no file collisions
		if !o.NoTypes {
			files["types.go"] = buff.Bytes()
		}
	}

	if !o.NoEmbedIDL {
		if err := embedIDL(g, i, m); err != nil {
			return nil, err
		}

		buff := new(bytes.Buffer)
		if err := g.Write(buff, nil /* fset */); err != nil {
			return nil, fmt.Errorf(
				"could not generate idl.go for %q: %v", m.ThriftPath, err)
		}

		files["idl.go"] = buff.Bytes()
	}

	// Services must be generated last because names of user-defined types take
	// precedence over the names we pick for the service types.
	if len(m.Services) > 0 {
		for _, serviceName := range sortStringKeys(m.Services) {
			service := m.Services[serviceName]

			// generateModule gets called only for those modules for which we
			// need to generate code. With --no-recurse, generateModule is
			// called only on the root file specified by the user and not its
			// included modules. Only services defined in these files are
			// considered root services; plugins will generate code only for
			// root services, even though they have information about the
			// whole service tree.
			if _, err := builder.AddRootService(service); err != nil {
				return nil, err
			}

			serviceFiles, err := Service(g, service)
			if err != nil {
				return nil, fmt.Errorf(
					"could not generate code for service %q: %v",
					serviceName, err)
			}

			if !o.NoServiceHelpers {
				for name, buff := range serviceFiles {
					files[name] = buff.Bytes()
				}
			}
		}
	}

	newFiles := make(map[string][]byte, len(files))
	for path, contents := range files {
		newFiles[filepath.Join(packageRelPath, path)] = contents
	}
	return newFiles, nil
}
1330398
func (n *NodeModuleRemoved) EvalTree() EvalNode {
	return &EvalOpFilter{
		Ops: []walkOperation{walkRefresh, walkApply, walkDestroy},
		Node: &EvalCheckModuleRemoved{
			Addr: n.Addr,
		},
	}
}
819754
func newNode(parent *node, entry Entry) *node {
	return &node{
		children: [2]*node{},
		entry:    entry,
		parent:   parent,
	}
}
574524
func (s *State) RootModule() *Module {
	if s == nil {
		panic("RootModule called on nil State")
	}
	return s.Modules[addrs.RootModuleInstance.String()]
}
1259327
func (m *Mrb) DefineModuleUnder(name string, outer *Class) *Class {
	if outer == nil {
		outer = m.ObjectClass()
	}

	cs := C.CString(name)
	defer C.free(unsafe.Pointer(cs))

	return newClass(m,
		C.mrb_define_module_under(m.state, outer.class, cs))
}
1204871
func (s *Application) NewModule(name string, middlewares ...interface{}) *Module {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	r := strings.SplitN(name, `@`, 2) //blog@www.blog.com
	var domain string
	if len(r) > 1 {
		name = r[0]
		domain = r[1]
	}
	a := NewModule(name, domain, s, middlewares...)
	if len(domain) > 0 {
		s.moduleHosts[domain] = a
	}
	s.moduleNames[name] = a
	return a
}