// GenerateType makes the body of a file implementing a set for type t.
775869
func (g *genSet) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
	sw := generator.NewSnippetWriter(w, c, "$", "$")
	sw.Do(setCode, g.args(t))
	sw.Do("func less$.type|public$(lhs, rhs $.type|raw$) bool {\n", g.args(t))
	g.lessBody(sw, t)
	sw.Do("}\n", g.args(t))
	return sw.Error()
}
579257
func (js jsonSchema) Generate(dir string) error {
	if js.Alias.Builtin {
		return nil // plain builtin type can't be a JSON
	}

	filename := filepath.Join(dir, js.filename())
	ctx := map[string]interface{}{
		"Content": js.String(),
	}
	return commons.GenerateFile(ctx, "./templates/golang/json_schema.tmpl", "json_schema", filename, true)
}
86396
func (g *Generator) generateEnum(enum *EnumDescriptor) {
	// The full type name
	typeName := enum.TypeName()
	// The full type name, CamelCased.
	ccTypeName := CamelCaseSlice(typeName)
	ccPrefix := enum.prefix()

	deprecatedEnum := ""
	if enum.GetOptions().GetDeprecated() {
		deprecatedEnum = deprecationComment
	}
	g.PrintComments(enum.path)
	g.P("type ", Annotate(enum.file, enum.path, ccTypeName), " int32", deprecatedEnum)
	g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()})
	g.P("const (")
	for i, e := range enum.Value {
		etorPath := fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i)
		g.PrintComments(etorPath)

		deprecatedValue := ""
		if e.GetOptions().GetDeprecated() {
			deprecatedValue = deprecationComment
		}

		name := ccPrefix + *e.Name
		g.P(Annotate(enum.file, etorPath, name), " ", ccTypeName, " = ", e.Number, " ", deprecatedValue)
		g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName})
	}
	g.P(")")
	g.P()
	g.P("var ", ccTypeName, "_name = map[int32]string{")
	generated := make(map[int32]bool) // avoid duplicate values
	for _, e := range enum.Value {
		duplicate := ""
		if _, present := generated[*e.Number]; present {
			duplicate = "// Duplicate value: "
		}
		g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",")
		generated[*e.Number] = true
	}
	g.P("}")
	g.P()
	g.P("var ", ccTypeName, "_value = map[string]int32{")
	for _, e := range enum.Value {
		g.P(strconv.Quote(*e.Name), ": ", e.Number, ",")
	}
	g.P("}")
	g.P()

	if !enum.proto3() {
		g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {")
		g.P("p := new(", ccTypeName, ")")
		g.P("*p = x")
		g.P("return p")
		g.P("}")
		g.P()
	}

	g.P("func (x ", ccTypeName, ") String() string {")
	g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))")
	g.P("}")
	g.P()

	if !enum.proto3() {
		g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {")
		g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`)
		g.P("if err != nil {")
		g.P("return err")
		g.P("}")
		g.P("*x = ", ccTypeName, "(value)")
		g.P("return nil")
		g.P("}")
		g.P()
	}

	var indexes []string
	for m := enum.parent; m != nil; m = m.parent {
		// XXX: skip groups?
		indexes = append([]string{strconv.Itoa(m.index)}, indexes...)
	}
	indexes = append(indexes, strconv.Itoa(enum.index))
	g.P("func (", ccTypeName, ") EnumDescriptor() ([]byte, []int) {")
	g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}")
	g.P("}")
	g.P()
	if enum.file.GetPackage() == "google.protobuf" && enum.GetName() == "NullValue" {
		g.P("func (", ccTypeName, `) XXX_WellKnownType() string { return "`, enum.GetName(), `" }`)
		g.P()
	}

	g.generateEnumRegistration(enum)
}
961339
func generateCRUD(buf io.Writer, t *cc.TranslationUnit, fnType string) {
	decls, err := bindgen.Get(t, functions)
	handleErr(err)

	var a = make(map[string][]string)
	switch fnType {
	case "create":
		fmt.Fprintf(buf, "creations = ")
	case "get":
		fmt.Fprintf(buf, "getFns = ")
	case "set":
		fmt.Fprintf(buf, "setFns = ")
	case "destroy":
		fmt.Fprintf(buf, "destructions = ")
	case "methods":
		fmt.Fprintf(buf, "methods = ")
	}

	var b map[string]struct{}

	for _, d := range decls {
		cs := d.(*bindgen.CSignature)
		params := cs.Parameters()

		if fnType != "methods" && !strings.Contains(strings.ToLower(cs.Name), fnType) {
			continue
		}
		if fnType == "methods" && len(params) == 0 {
			continue
		}

		switch fnType {
		case "create":
			for i := len(params) - 1; i >= 0; i-- {
				p := params[i]
				if !bindgen.IsConstType(p.Type()) && bindgen.IsPointer(p.Type()) {
					typ := nameOfType(p.Type())
					a[typ] = append(a[typ], cs.Name)
				}
			}

		case "set", "destroy":
			p := params[0]
			typ := nameOfType(p.Type())
			if typ == "cudnnHandle_t" && len(params) > 1 {
				p = params[1]
				typ = nameOfType(p.Type())
			}
			a[typ] = append(a[typ], cs.Name)
		case "methods":
			// if strings.Contains(strings.ToLower(cs.Name), "get") {
			// 	continue
			// }
			if _, ok := ignored[cs.Name]; ok {
				continue
			}
			if alreadyGenIn(cs.Name, creations, setFns, destructions) {
				continue
			}

			p := params[0]
			typ := nameOfType(p.Type())
			a[typ] = append(a[typ], cs.Name)
		}
	}
	fmt.Fprintf(buf, "%# v\n\n", pretty.Formatter(a))

	// set the actual thing if not set
	// lisp users just shake their head in disappointment
	switch fnType {
	case "create":
		creations = a
	case "set":
		setFns = a
	case "destroy":
		destructions = a
	case "methods":
		methods = a
		if b != nil {
			fmt.Fprintf(buf, "orphaned = %# v\n\n", pretty.Formatter(b))
			orphaned = b
		}
	}
}
740279
func (parser *Parser) ParseType(astFile *ast.File) {
	if _, ok := parser.TypeDefinitions[astFile.Name.String()]; !ok {
		parser.TypeDefinitions[astFile.Name.String()] = make(map[string]*ast.TypeSpec)
	}

	for _, astDeclaration := range astFile.Decls {
		if generalDeclaration, ok := astDeclaration.(*ast.GenDecl); ok && generalDeclaration.Tok == token.TYPE {
			for _, astSpec := range generalDeclaration.Specs {
				if typeSpec, ok := astSpec.(*ast.TypeSpec); ok {
					typeName := fmt.Sprintf("%v", typeSpec.Type)
					// check if its a custom primitive type
					if IsGolangPrimitiveType(typeName) {
						parser.CustomPrimitiveTypes[typeSpec.Name.String()] = TransToValidSchemeType(typeName)
					} else {
						parser.TypeDefinitions[astFile.Name.String()][typeSpec.Name.String()] = typeSpec
					}

				}
			}
		}
	}
}
286035
func (g *deepCopyGenerator) ReplaceType(pkgPath, name string, t interface{}) {
	g.replace[pkgPathNamePair{pkgPath, name}] = reflect.TypeOf(t)
}
1129808
func Generate(schema *rdl.Schema, params *GeneratorParams) error {
	name := strings.ToLower(string(schema.Name))
	outdir := params.Outdir
	if outdir == "" {
		outdir = "."
		name = name + "_model.go"
	} else if strings.HasSuffix(outdir, ".go") {
		name = filepath.Base(outdir)
		outdir = filepath.Dir(outdir)
	} else {
		name = name + "_model.go"
	}
	err := os.MkdirAll(outdir, 0755)
	if err != nil {
		return err
	}
	filepath := outdir + "/" + name
	out, file, _, err := genutil.OutputWriter(filepath, "", ".go")
	if err != nil {
		return err
	}
	if file != nil {
		defer func() {
			file.Close()
			err := goFmt(filepath)
			if err != nil {
				fmt.Println("Warning: could not format go code:", err)
			}
		}()
	}
	gen := &modelGenerator{
		registry:       rdl.NewTypeRegistry(schema),
		schema:         schema,
		writer:         out,
		librdl:         params.LibRdl,
		prefixEnums:    params.PrefixEnums,
		precise:        params.PreciseTypes,
		err:            nil,
		untaggedUnions: params.UntaggedUnions,
		ns:             params.Namespace,
		rdl:            schema.Name == "rdl",
	}
	gen.emitHeader(params.Banner)
	if gen.err == nil {
		for _, t := range schema.Types {
			gen.emitType(t)
		}
	}
	out.Flush()
	if gen.err == nil {
		if params.GenerateSchema {
			gen.err = GenerateGoSchema(params.Banner, schema, outdir, params.Namespace, params.LibRdl, params.PrefixEnums)
		}
	}
	return gen.err
}
880196
func generated(filename string) bool {
	return filepath.Base(filename) == boxFilename ||
		strings.HasSuffix(filename, "."+boxFilename) ||
		strings.HasSuffix(filename, sysoBoxSuffix)
}
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
}
1049049
func (o *object) generate(dir string) error {
	o.handleAdvancedType()

	// generate enums
	for _, f := range o.Fields {
		if f.Enum != nil {
			if err := f.Enum.generate(dir); err != nil {
				return err
			}
		}
	}

	if o.Enum != nil {
		return o.Enum.generate(dir)
	}
	filename := filepath.Join(dir, o.Name()+".nim")
	if err := commons.GenerateFile(o, "./templates/nim/object_nim.tmpl", "object_nim", filename, true); err != nil {
		return err
	}
	return nil
}
1202822
func (g NamespaceGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	err := generate.ValidateParams(g.ParamNames(), genericParams)
	if err != nil {
		return nil, err
	}
	params := map[string]string{}
	for key, value := range genericParams {
		strVal, isString := value.(string)
		if !isString {
			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
		}
		params[key] = strVal
	}
	delegate := &NamespaceGeneratorV1{Name: params["name"]}
	return delegate.StructuredGenerate()
}
1336180
func GenerateTemplate(filename, templateSource string, args map[string]interface{}) (err error) {
	tmpl := template.Must(template.New("").Parse(templateSource))

	var b bytes.Buffer
	if err = tmpl.Execute(&b, args); err != nil {
		return NewBuildIfError(err, "ExecuteTemplate: Execute failed")
	}
	sourceCode := b.String()
	filePath := filepath.Dir(filename)
	if !DirExists(filePath) {
		err = os.MkdirAll(filePath, 0777)
		if err != nil && !os.IsExist(err) {
			return NewBuildIfError(err, "Failed to make directory", "dir", filePath)
		}
	}

	// Create the file
	file, err := os.Create(filename)
	if err != nil {
		Logger.Fatal("Failed to create file", "error", err)
		return
	}
	defer func() {
		_ = file.Close()
	}()

	if _, err = file.WriteString(sourceCode); err != nil {
		Logger.Fatal("Failed to write to file: ", "error", err)
	}

	return
}
844659
func Generate() (files []string, err error) {
	var (
		outDir, ver  string
		timeout      time.Duration
		scheme, host string
		noexample    bool
	)

	set := flag.NewFlagSet("client", flag.PanicOnError)
	set.StringVar(&outDir, "out", "", "")
	set.String("design", "", "")
	set.DurationVar(&timeout, "timeout", time.Duration(20)*time.Second, "")
	set.StringVar(&scheme, "scheme", "", "")
	set.StringVar(&host, "host", "", "")
	set.StringVar(&ver, "version", "", "")
	set.BoolVar(&noexample, "noexample", false, "")
	set.Parse(os.Args[1:])

	// First check compatibility
	if err := codegen.CheckVersion(ver); err != nil {
		return nil, err
	}

	// Now proceed
	g := &Generator{OutDir: outDir, Timeout: timeout, Scheme: scheme, Host: host, NoExample: noexample, API: design.Design}

	return g.Generate()
}
630342
func (uow *UnitOfWork) Generate(templateFile string, output string) {
	templateFileParts := strings.Split(templateFile, "/")
	templateName := templateFileParts[len(templateFileParts)-1]

	tmpl, err := template.New(templateName).ParseFiles(templateFile)
	if err != nil {
		printErrorf("ERROR: %s\n", err)
		return
	}

	executeTemplate := func(outputFile string, templateInfo interface{}) {
		writer := os.Stdout
		if len(outputFile) > 0 {
			writer, _ = os.Create(outputFile)
		}
		err = tmpl.Execute(writer, templateInfo)
		if err != nil {
			printErrorf("ERROR: %s\n", err)
		}
	}

	if strings.Contains(output, "%s") {
		for _, container := range uow.TargetedInfo() {
			executeTemplate(fmt.Sprintf(output, container.PrefixedName()), container)
		}
	} else {
		tmplInfo := struct {
			Containers []ContainerInfo
		}{
			Containers: uow.TargetedInfo(),
		}
		executeTemplate(output, tmplInfo)
	}
}
1017740
func (domain *Domain) GenerateCompiler(packageName string, license string, imports []string) string {
	code := &printer.Code{}
	code.Print(license)
	code.Print("// THIS FILE IS AUTOMATICALLY GENERATED.\n")

	// generate package declaration
	code.Print("package %s\n", packageName)

	code.Print("import (")
	for _, filename := range imports {
		code.Print("\"" + filename + "\"")
	}
	code.Print(")\n")

	// generate a simple Version() function
	code.Print("// Version returns the package name (and OpenAPI version).")
	code.Print("func Version() string {")
	code.Print("  return \"%s\"", packageName)
	code.Print("}\n")

	typeNames := domain.sortedTypeNames()

	regexPatterns := &patternNames{
		prefix: "pattern",
		specialCase: map[string]func(string) string{
			"^x-": func(variable string) string { return fmt.Sprintf("strings.HasPrefix(%s, \"x-\")", variable) },
			"^/":  func(variable string) string { return fmt.Sprintf("strings.HasPrefix(%s, \"/\")", variable) },
			"^":   func(_ string) string { return "true" },
		},
	}

	// generate NewX() constructor functions for each type
	for _, typeName := range typeNames {
		domain.generateConstructorForType(code, typeName, regexPatterns)
	}

	// generate ResolveReferences() methods for each type
	for _, typeName := range typeNames {
		domain.generateResolveReferencesMethodsForType(code, typeName)
	}

	// generate ToRawInfo() methods for each type
	for _, typeName := range typeNames {
		domain.generateToRawInfoMethodForType(code, typeName)
	}

	domain.generateConstantVariables(code, regexPatterns)

	return code.String()
}
264832
func Generate(schema *rdl.Schema, params *GeneratorParams) error {
	packageDir, err := GenerationDir(params.Outdir, schema, params.Namespace)
	if err != nil {
		return err
	}
	//	getSetters := GenerationBoolOptionSet(options, "getsetters")
	registry := rdl.NewTypeRegistry(schema)
	for _, t := range schema.Types {
		tName, _, _ := rdl.TypeInfo(t)
		if strings.HasPrefix(string(tName), "rdl.") {
			continue
		}
		err := generateJavaType(params.Banner, schema, registry, packageDir, t, params.Namespace, params.GetSetters)
		if err != nil {
			return err
		}
	}
	cName := capitalize(string(schema.Name)) + "Schema"
	out, file, _, err := genutil.OutputWriter(packageDir, cName, ".java")
	if err != nil {
		return err
	}
	err = GenerateSchema(schema, cName, out, params.Namespace, params.Banner)
	out.Flush()
	file.Close()
	if err != nil {
		return err
	}
	return nil
}
815499
func (s *ComputeResource) SetType(v string) *ComputeResource {
	s.Type = &v
	return s
}