/*
 * Operator generators.
 */
331280
func (a *expr) genConstant(v Value) {
	switch a.t.lit().(type) {
	case *boolType:
		a.eval = func(t *Thread) bool { return v.(BoolValue).Get(t) }
	case *uintType:
		a.eval = func(t *Thread) uint64 { return v.(UintValue).Get(t) }
	case *intType:
		a.eval = func(t *Thread) int64 { return v.(IntValue).Get(t) }
	case *idealIntType:
		val := v.(IdealIntValue).Get()
		a.eval = func() *big.Int { return val }
	case *floatType:
		a.eval = func(t *Thread) float64 { return v.(FloatValue).Get(t) }
	case *idealFloatType:
		val := v.(IdealFloatValue).Get()
		a.eval = func() *big.Rat { return val }
	case *stringType:
		a.eval = func(t *Thread) string { return v.(StringValue).Get(t) }
	case *ArrayType:
		a.eval = func(t *Thread) ArrayValue { return v.(ArrayValue).Get(t) }
	case *StructType:
		a.eval = func(t *Thread) StructValue { return v.(StructValue).Get(t) }
	case *PtrType:
		a.eval = func(t *Thread) Value { return v.(PtrValue).Get(t) }
	case *FuncType:
		a.eval = func(t *Thread) Func { return v.(FuncValue).Get(t) }
	case *SliceType:
		a.eval = func(t *Thread) Slice { return v.(SliceValue).Get(t) }
	case *MapType:
		a.eval = func(t *Thread) Map { return v.(MapValue).Get(t) }
	default:
		log.Panicf("unexpected constant type %v at %v", a.t, a.pos)
	}
}
877779
func (g *Generator) Out() {
	if len(g.indent) > 0 {
		g.indent = g.indent[1:]
	}
}
865515
func (p Prefixed) Generate() string {
	if p.Len == 0 {
		p.Len = PrefixedDefaultLen
	}

	if len(p.Acceptable) == 0 {
		p.Acceptable = PrefixedDefaultAcceptable
	}

	if p.RandGenerator == nil {
		p.RandGenerator = rand.Reader
	}

	builder := bytes.NewBufferString(p.Prefix)

	max := big.NewInt(int64(len(p.Acceptable)))

	for i := uint8(0); i < p.Len; i++ {
		result, err := rand.Int(p.RandGenerator, max)
		if err != nil {
			panic(err)
		}
		builder.WriteRune(p.Acceptable[result.Int64()])
	}
	return builder.String()
}
61639
func (codegen *CodeGenerator) Generate() (string, error) {
	for index, rawSchema := range codegen.rawSchemas {
		parsedSchema, err := ParseSchema(rawSchema)
		if err != nil {
			return "", err
		}

		schema, ok := parsedSchema.(*RecordSchema)
		if !ok {
			return "", errors.New("Not a Record schema.")
		}
		schemaInfo, err := newRecordSchemaInfo(schema)
		if err != nil {
			return "", err
		}

		buffer := &bytes.Buffer{}
		codegen.codeSnippets = append(codegen.codeSnippets, buffer)

		// write package and import only once
		if index == 0 {
			err = codegen.writePackageName(schemaInfo)
			if err != nil {
				return "", err
			}

			err = codegen.writeImportStatement()
			if err != nil {
				return "", err
			}
		}

		err = codegen.writeStruct(schemaInfo)
		if err != nil {
			return "", err
		}
	}

	formatted, err := format.Source([]byte(codegen.collectResult()))
	if err != nil {
		return "", err
	}

	return string(formatted), nil
}
1046537
func NewGenerator(options ...Option) *Generator {
	g := &Generator{}

	for _, option := range options {
		option(g)
	}

	return g
}
815857
func Generate(args map[string]string) string {
	p := pattern.New(args)

	return p.SvgStr()
}
1226534
func (i *VarAdder) Generate(next ContextHandler) ContextHandler {
	return HandlerFunc(func(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
		next.ServeHTTPC(context.WithValue(ctx, i.Key, i.Value), rw, r)
	})
}
1234085
func Generate(ctx context.Context, in Inputs) (*State, error) {
	state := &State{Inputs: in}
	ctx = withState(ctx, state)

	// All available functions implemented in go.
	predeclared := starlark.StringDict{
		// Part of public API of the generator.
		"fail":       builtins.Fail,
		"proto":      starlarkproto.ProtoLib()["proto"],
		"stacktrace": builtins.Stacktrace,
		"struct":     builtins.Struct,
		"to_json":    builtins.ToJSON,

		// '__native__' is NOT public API. It should be used only through public
		// @stdlib functions.
		"__native__": native(starlark.StringDict{
			"ctor":          builtins.Ctor,
			"genstruct":     builtins.GenStruct,
			"re_submatches": builtins.RegexpMatcher("submatches"),
		}),
	}
	for k, v := range in.testPredeclared {
		predeclared[k] = v
	}

	// Expose @stdlib, @proto and __main__ package. All have no externally
	// observable state of their own, but they call low-level __native__.*
	// functions that manipulate 'state' by getting it through the context.
	pkgs := embeddedPackages()
	pkgs[interpreter.MainPkg] = in.Code
	pkgs["proto"] = protoLoader() // see protos.go

	// Capture details of fail(...) calls happening inside Starlark code.
	failures := builtins.FailureCollector{}

	// Execute the config script in this environment. Return errors unwrapped so
	// that callers can sniff out various sorts of Starlark errors.
	intr := interpreter.Interpreter{
		Predeclared: predeclared,
		Packages:    pkgs,

		PreExec:  func(th *starlark.Thread, pkg, mod string) { state.vars.OpenScope(th) },
		PostExec: func(th *starlark.Thread, pkg, mod string) { state.vars.CloseScope(th) },

		ThreadModifier: func(th *starlark.Thread) {
			if !in.testDisableFailureCollector {
				failures.Install(th)
			}
			if in.testThreadModifier != nil {
				in.testThreadModifier(th)
			}
		},
	}

	// Load builtins.star, and then execute the user-supplied script.
	var err error
	if err = intr.Init(ctx); err == nil {
		_, err = intr.ExecModule(ctx, interpreter.MainPkg, in.Entry)
	}
	if err != nil {
		if f := failures.LatestFailure(); f != nil {
			err = f // prefer this error, it has custom stack trace
		}
		return nil, state.err(err)
	}

	// Executing the script (with all its dependencies) populated the graph.
	// Finalize it. This checks there are no dangling edges, freezes the graph,
	// and makes it queryable, so generator callbacks can traverse it.
	if errs := state.graph.Finalize(); len(errs) != 0 {
		return nil, state.err(errs...)
	}

	// The script registered a bunch of callbacks that take the graph and
	// transform it into actual output config files. Run these callbacks now.
	genCtx := newGenCtx()
	if errs := state.generators.call(intr.Thread(ctx), genCtx); len(errs) != 0 {
		return nil, state.err(errs...)
	}
	output, err := genCtx.assembleOutput(!in.testOmitHeader)
	if err != nil {
		return nil, state.err(err)
	}
	state.Output = output

	if len(state.errors) != 0 {
		return nil, state.errors
	}
	return state, nil
}
495699
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	codegen.Reserved[g.Target] = true

	os.RemoveAll(g.OutDir)

	if err := os.MkdirAll(g.OutDir, 0755); err != nil {
		return nil, err
	}
	g.genfiles = []string{g.OutDir}
	if err := g.generateContexts(); err != nil {
		return nil, err
	}
	if err := g.generateControllers(); err != nil {
		return nil, err
	}
	if err := g.generateSecurity(); err != nil {
		return nil, err
	}
	if err := g.generateHrefs(); err != nil {
		return nil, err
	}
	if err := g.generateMediaTypes(); err != nil {
		return nil, err
	}
	if err := g.generateUserTypes(); err != nil {
		return nil, err
	}
	if !g.NoTest {
		if err := g.generateResourceTest(); err != nil {
			return nil, err
		}
	}

	return g.genfiles, nil
}
1250524
func AddGeneratorFlags(cmd *cobra.Command, defaultGenerator string) {
	cmd.Flags().String("generator", defaultGenerator, "The name of the API generator to use.")
	AddDryRunFlag(cmd)
}
1299011
func (g *Generator) GenerateAllFiles() {
	// Initialize the plugins
	for _, p := range plugins {
		p.Init(g)
	}
	// Generate the output. The generator runs for every file, even the files
	// that we don't generate output for, so that we can collate the full list
	// of exported symbols to support public imports.
	genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles))
	for _, file := range g.genFiles {
		genFileMap[file] = true
	}
	for _, file := range g.allFiles {
		g.Reset()
		g.annotations = nil
		g.writeOutput = genFileMap[file]
		g.generate(file)
		if !g.writeOutput {
			continue
		}
		fname := file.goFileName(g.pathType)
		g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
			Name:    proto.String(fname),
			Content: proto.String(g.String()),
		})
		if g.annotateCode {
			// Store the generated code annotations in text, as the protoc plugin protocol requires that
			// strings contain valid UTF-8.
			g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
				Name:    proto.String(file.goFileName(g.pathType) + ".meta"),
				Content: proto.String(proto.CompactTextString(&descriptor.GeneratedCodeInfo{Annotation: g.annotations})),
			})
		}
	}
}
944257
func NewIDGenerator(opts ...IDGeneratorOp) *IDGenerator {
	gen := &IDGenerator{}
	for _, f := range opts {
		f(gen)
	}
	if gen.Generator == nil {
		gen.Generator = snowflake.New(rand.Intn(1023))
	}
	return gen
}
92915
func (a *APIDefinition) RandomGenerator() *RandomGenerator {
	if a.rand == nil {
		a.rand = NewRandomGenerator(a.Name)
	}
	return a.rand
}
383703
func NewGenerator(pkg, target string) (*Generator, error) {
	var err error
	if pkg == "" || pkg[0] == '.' {
		pkg, err = filepath.Abs(filepath.Clean(pkg))
		if err != nil {
			return nil, err
		}
		pkg = gogenutil.StripGopath(pkg)
	}
	p, err := importer.Default().Import(pkg)
	if err != nil {
		return nil, err
	}
	obj := p.Scope().Lookup(target)
	if obj == nil {
		return nil, fmt.Errorf("struct %s missing", target)
	}
	if _, ok := obj.Type().Underlying().(*types.Struct); !ok {
		return nil, fmt.Errorf("%s should be an struct, was %s", target, obj.Type().Underlying())
	}
	return &Generator{
		targetName: target,
		pkg:        p,
		target:     obj.Type().Underlying().(*types.Struct),
	}, nil
}
660520
func (g Generator) Methods() []Method {
	numMethods := g.iface.NumMethods()
	methods := make([]Method, numMethods)
	for i := 0; i < numMethods; i++ {
		methods[i] = Method{&g, g.iface.Method(i)}
	}
	return methods
}
261767
func NewGenerator(options *Options) *Generator {
	var g = &Generator{}
	// first we validate the flags
	if err := options.Validate(); err != nil {
		panic(err)
	}
	g.options = options
	// we initiate the values on the generator
	g.init()
	return g
}
326959
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	if g.Timeout == 0 {
		g.Timeout = 20 * time.Second
	}
	if g.Scheme == "" && len(g.API.Schemes) > 0 {
		g.Scheme = g.API.Schemes[0]
	}
	if g.Scheme == "" {
		g.Scheme = "http"
	}
	if g.Host == "" {
		g.Host = g.API.Host
	}
	if g.Host == "" {
		return nil, fmt.Errorf("missing host value, set it with --host")
	}

	g.OutDir = filepath.Join(g.OutDir, "js")
	if err := os.RemoveAll(g.OutDir); err != nil {
		return nil, err
	}
	if err := os.MkdirAll(g.OutDir, 0755); err != nil {
		return nil, err
	}
	g.genfiles = append(g.genfiles, g.OutDir)

	// Generate client.js
	exampleAction, err := g.generateJS(filepath.Join(g.OutDir, "client.js"))
	if err != nil {
		return
	}

	// Generate axios.html
	if err = g.generateAxiosJS(); err != nil {
		return
	}

	if exampleAction != nil && !g.NoExample {
		// Generate index.html
		if err = g.generateIndexHTML(filepath.Join(g.OutDir, "index.html"), exampleAction); err != nil {
			return
		}

		// Generate example
		if err = g.generateExample(); err != nil {
			return
		}
	}

	return g.genfiles, nil
}