// AddModule adds the module with the given path to the state.
//
// This should be the preferred method to add module states since it
// allows us to optimize lookups later as well as control sorting.
501997
func (s *State) AddModule(path addrs.ModuleInstance) *ModuleState {
	s.Lock()
	defer s.Unlock()

	return s.addModule(path)
}
97860
func (d *Diff) AddModule(path addrs.ModuleInstance) *ModuleDiff {
	// Lower the new-style address into a legacy-style address.
	// This requires that none of the steps have instance keys, which is
	// true for all addresses at the time of implementing this because
	// "count" and "for_each" are not yet implemented for modules.
	legacyPath := make([]string, len(path))
	for i, step := range path {
		if step.InstanceKey != addrs.NoKey {
			// FIXME: Once the rest of Terraform is ready to use count and
			// for_each, remove all of this and just write the addrs.ModuleInstance
			// value itself into the ModuleState.
			panic("diff cannot represent modules with count or for_each keys")
		}

		legacyPath[i] = step.Name
	}

	m := &ModuleDiff{Path: legacyPath}
	m.init()
	d.Modules = append(d.Modules, m)
	return m
}
25426
func GetModule(name string) (interfaces.Module, error) {
	if m, ok := modulesMap[name]; ok {
		return m, nil
	}
	return nil, fmt.Errorf("module with name %s not found", name)
}
1152525
func (m *Module) AddController(ct *ControllerType) {
	m.ControllerTypeList = append(m.ControllerTypeList, ct)
}
887042
func (intr *Interpreter) runModule(ctx context.Context, key moduleKey, kind ThreadKind) (starlark.StringDict, error) {
	// Grab the source code.
	dict, src, err := intr.invokeLoader(key)
	switch {
	case err != nil:
		return nil, err
	case dict != nil:
		// This is a native module constructed in Go, no need to interpret it.
		return dict, nil
	}

	// Otherwise make a thread for executing the code. We do not reuse threads
	// between modules. All global state is passed through intr.globals,
	// intr.modules and ctx.
	th := intr.Thread(ctx)
	th.Load = func(th *starlark.Thread, module string) (starlark.StringDict, error) {
		key, err := makeModuleKey(module, th)
		if err != nil {
			return nil, err
		}
		dict, err := intr.LoadModule(ctx, key.pkg, key.path)
		// See comment in execBuiltin about why we extract EvalError backtrace into
		// new error.
		if evalErr, ok := err.(*starlark.EvalError); ok {
			err = fmt.Errorf("%s", evalErr.Backtrace())
		}
		return dict, err
	}

	// Let builtins know what this thread is doing. Some calls (most notably Exec
	// itself) are allowed only from exec'ing threads, not from load'ing ones.
	th.SetLocal(threadKindKey, kind)
	// Let builtins (and in particular makeModuleKey and LoadSource) know the
	// package and the module that the thread executes.
	th.SetLocal(threadModKey, key)

	if kind == ThreadExecing {
		if intr.PreExec != nil {
			intr.PreExec(th, key.pkg, key.path)
		}
		if intr.PostExec != nil {
			defer intr.PostExec(th, key.pkg, key.path)
		}
	}

	// Execute the module. It may 'load' or 'exec' other modules inside, which
	// will either call LoadModule or ExecModule.
	//
	// Use user-friendly module name (with omitted "@__main__") for error messages
	// and stack traces to avoid confusing the user.
	return starlark.ExecFile(th, key.String(), src, intr.globals)
}
813094
func AddModule(id string, m ModuleLoader) {
	globalMu.Lock()
	globalModules[id] = m
	globalMu.Unlock()
}
473416
func RegisterModuleAfter(module interfaces.Module, name string) error {
	if err := alreadyRegistered(name); err != nil {
		return err
	}

	modulesMap[name] = module
	modulesArr = append(modulesArr, moduleWrapper{
		module: module,
		name:   name,
	})

	return nil
}
878391
func (b *Builder) addFile(pkgPath importPathString, path string, src []byte, userRequested bool) error {
	for _, p := range b.parsed[pkgPath] {
		if path == p.name {
			klog.V(5).Infof("addFile %s %s already parsed, skipping", pkgPath, path)
			return nil
		}
	}
	klog.V(6).Infof("addFile %s %s", pkgPath, path)
	p, err := parser.ParseFile(b.fset, path, src, parser.DeclarationErrors|parser.ParseComments)
	if err != nil {
		return err
	}

	// This is redundant with addDir, but some tests call AddFileForTest, which
	// call into here without calling addDir.
	b.userRequested[pkgPath] = userRequested || b.userRequested[pkgPath]

	b.parsed[pkgPath] = append(b.parsed[pkgPath], parsedFile{path, p})
	for _, c := range p.Comments {
		position := b.fset.Position(c.End())
		b.endLineToCommentGroup[fileLine{position.Filename, position.Line}] = c
	}

	// We have to get the packages from this specific file, in case the
	// user added individual files instead of entire directories.
	if b.importGraph[pkgPath] == nil {
		b.importGraph[pkgPath] = map[string]struct{}{}
	}
	for _, im := range p.Imports {
		importedPath := strings.Trim(im.Path.Value, `"`)
		b.importGraph[pkgPath][importedPath] = struct{}{}
	}
	return nil
}
1196144
func Compile(path string, opts ...Option) (*Module, error) {
	c := newCompiler()
	for _, opt := range opts {
		opt(&c)
	}

	m, err := c.load(path)
	if err != nil {
		return nil, err
	}

	err = m.Walk(func(m *Module) error {
		if err := c.link(m); err != nil {
			return compileError{
				Target: m.ThriftPath,
				Reason: err,
			}
		}
		return nil
	})
	return m, err
}
1073446
func NewModules() *Modules {
	return &Modules{
		Submodules: make(map[string]*Submodule),
		raw:        format.New(),
	}
}
33447
func LoadModule(dir string) (*tfconfig.Module, tfdiags.Diagnostics) {
	mod, diags := tfconfig.LoadModule(dir)
	return mod, wrapDiagnostics(diags)
}
432940
func listModules() ([]string, error) {
	fModules, err := os.Open(modulesFilepath)
	if err != nil {
		return nil, fmt.Errorf(
			"failed to open modules information at %s: %s",
			modulesFilepath, err)
	}
	defer fModules.Close()
	return parseModulesFile(fModules)
}
1161441
func (ctxt *Context) AddDirectory(path string) (*types.Package, error) {
	return ctxt.builder.AddDirectoryTo(path, &ctxt.Universe)
}
419857
func MustParseModule(input string) *Module {
	parsed, err := ParseModule("", input)
	if err != nil {
		panic(err)
	}
	return parsed
}
237555
func loModule(L *LState) int {
	name := L.CheckString(1)
	loaded := L.GetField(L.Get(RegistryIndex), "_LOADED")
	tb := L.GetField(loaded, name)
	if _, ok := tb.(*LTable); !ok {
		tb = L.FindTable(L.Get(GlobalsIndex).(*LTable), name, 1)
		if tb == LNil {
			L.RaiseError("name conflict for module: %v", name)
		}
		L.SetField(loaded, name, tb)
	}
	if L.GetField(tb, "_NAME") == LNil {
		L.SetField(tb, "_M", tb)
		L.SetField(tb, "_NAME", LString(name))
		names := strings.Split(name, ".")
		pname := ""
		if len(names) > 1 {
			pname = strings.Join(names[:len(names)-1], ".") + "."
		}
		L.SetField(tb, "_PACKAGE", LString(pname))
	}

	caller := L.currentFrame.Parent
	if caller == nil {
		L.RaiseError("no calling stack.")
	} else if caller.Fn.IsG {
		L.RaiseError("module() can not be called from GFunctions.")
	}
	L.SetFEnv(caller.Fn, tb)

	top := L.GetTop()
	for i := 2; i <= top; i++ {
		L.Push(L.Get(i))
		L.Push(tb)
		L.Call(1, 0)
	}
	L.Push(tb)
	return 1
}
158210
func (m *Module) Module() string {
	return fmt.Sprintf("%s/%s/%s", m.RawNamespace, m.RawName, m.RawProvider)
}
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
}