// compilesModelSpec examines typ using reflection, parses its fields,
// and returns a modelSpec.
770784
func compileModelSpec(typ reflect.Type) (*modelSpec, error) {
	ms := &modelSpec{
		name:         getDefaultModelSpecName(typ),
		fieldsByName: map[string]*fieldSpec{},
		typ:          typ,
	}

	// Iterate through fields
	elem := typ.Elem()
	numFields := elem.NumField()
	for i := 0; i < numFields; i++ {
		field := elem.Field(i)
		// Skip unexported fields. Prior to go 1.6, field.PkgPath won't give us
		// the behavior we want. Unlike packages such as encoding/json and
		// encoding/gob, Zoom does not save unexported embedded structs with
		// exported fields. So instead, we check if the first character of the
		// field name is lowercase.
		if strings.ToLower(field.Name[0:1]) == field.Name[0:1] {
			continue
		}

		// Skip the RandomID field
		if field.Type == reflect.TypeOf(RandomID{}) {
			continue
		}

		// Parse the "redis" tag
		tag := field.Tag
		redisTag := tag.Get("redis")
		if redisTag == "-" {
			continue // skip field
		}
		fs := &fieldSpec{name: field.Name, typ: field.Type}
		ms.fieldsByName[fs.name] = fs
		ms.fields = append(ms.fields, fs)
		if redisTag != "" {
			fs.redisName = redisTag
		} else {
			fs.redisName = fs.name
		}

		// Parse the "zoom" tag (currently only "index" is supported)
		zoomTag := tag.Get("zoom")
		shouldIndex := false
		if zoomTag != "" {
			options := strings.Split(zoomTag, ",")
			for _, op := range options {
				switch op {
				case "index":
					shouldIndex = true
				default:
					return nil, fmt.Errorf("zoom: unrecognized option specified in struct tag: %s", op)
				}
			}
		}

		// Detect the kind of the field and (if applicable) the kind of the index
		if typeIsPrimative(field.Type) {
			// Primitive
			fs.kind = primativeField
			if shouldIndex {
				if err := setIndexKind(fs, field.Type); err != nil {
					return nil, err
				}
			}
		} else if field.Type.Kind() == reflect.Ptr && typeIsPrimative(field.Type.Elem()) {
			// Pointer to a primitive
			fs.kind = pointerField
			if shouldIndex {
				if err := setIndexKind(fs, field.Type.Elem()); err != nil {
					return nil, err
				}
			}
		} else {
			// All other types are considered inconvertible
			if shouldIndex {
				return nil, fmt.Errorf("zoom: Requested index on unsupported type %s", field.Type)
			}
			fs.kind = inconvertibleField
		}
	}
	return ms, nil
}
921518
func (b *OpenAPI3Builder) buildTypeFromSchemaOrReference(
	name string,
	schemaOrReference *openapiv3.SchemaOrReference) (t *Type, err error) {
	if schema := schemaOrReference.GetSchema(); schema != nil {
		t = &Type{}
		t.Name = name
		t.Description = "implements the service definition of " + name
		t.Fields = make([]*Field, 0)
		if schema.Properties != nil {
			if len(schema.Properties.AdditionalProperties) > 0 {
				// If the schema has properties, generate a struct.
				t.Kind = TypeKind_STRUCT
			}
			for _, pair2 := range schema.Properties.AdditionalProperties {
				if schema := pair2.Value; schema != nil {
					var f Field
					f.Name = pair2.Name
					f.Kind, f.Type, f.Format = b.typeForSchemaOrReference(schema)
					f.Serialize = true
					t.addField(&f)
				}
			}
		}
		if len(t.Fields) == 0 {
			if schema.AdditionalProperties != nil {
				// If the schema has no fixed properties and additional properties of a specified type,
				// generate a map pointing to objects of that type.
				t.Kind = TypeKind_OBJECT
				t.ContentType = typeForRef(schema.AdditionalProperties.GetSchemaOrReference().GetReference().GetXRef())
			}
		}
		return t, err
	} else {
		return nil, errors.New("unable to determine service type for referenced schema " + name)
	}
}
340779
func NewTemplateSpec(project, ref, version, name string) *Quest_TemplateSpec {
	return &Quest_TemplateSpec{
		Project: project,
		Ref:     ref,
		Version: version,
		Name:    name,
	}
}
385361
func (table *TableElem) Compile(d Dialect, params *Parameters) string {
	return fmt.Sprintf(`"%s"`, table.String())
}
391288
func (c *Compiler) Compile(ctx context.Context) (*flux.Spec, error) {
	transpiler := NewTranspilerWithConfig(
		c.dbrpMappingSvc,
		Config{
			Cluster:                c.Cluster,
			DefaultDatabase:        c.DB,
			DefaultRetentionPolicy: c.RP,
		},
	)
	return transpiler.Transpile(ctx, c.Query)
}
1059355
func ModelInfoFromParams(info params.ModelInfo, now time.Time) (ModelInfo, error) {
	ownerTag, err := names.ParseUserTag(info.OwnerTag)
	if err != nil {
		return ModelInfo{}, errors.Trace(err)
	}
	cloudTag, err := names.ParseCloudTag(info.CloudTag)
	if err != nil {
		return ModelInfo{}, errors.Trace(err)
	}
	modelInfo := ModelInfo{
		ShortName:      info.Name,
		Name:           jujuclient.JoinOwnerModelName(ownerTag, info.Name),
		Type:           model.ModelType(info.Type),
		UUID:           info.UUID,
		ControllerUUID: info.ControllerUUID,
		IsController:   info.IsController,
		Owner:          ownerTag.Id(),
		Life:           string(info.Life),
		Cloud:          cloudTag.Id(),
		CloudRegion:    info.CloudRegion,
	}
	if info.AgentVersion != nil {
		modelInfo.AgentVersion = info.AgentVersion.String()
	}
	// Although this may be more performance intensive, we have to use reflection
	// since structs containing map[string]interface {} cannot be compared, i.e
	// cannot use simple '==' here.
	if !reflect.DeepEqual(info.Status, params.EntityStatus{}) {
		modelInfo.Status = &ModelStatus{
			Current: info.Status.Status,
			Message: info.Status.Info,
			Since:   FriendlyDuration(info.Status.Since, now),
		}
	}
	if info.Migration != nil {
		status := modelInfo.Status
		if status == nil {
			status = &ModelStatus{}
			modelInfo.Status = status
		}
		status.Migration = info.Migration.Status
		status.MigrationStart = FriendlyDuration(info.Migration.Start, now)
		status.MigrationEnd = FriendlyDuration(info.Migration.End, now)
	}

	if info.ProviderType != "" {
		modelInfo.ProviderType = info.ProviderType

	}
	if len(info.Users) != 0 {
		modelInfo.Users = ModelUserInfoFromParams(info.Users, now)
	}
	if len(info.Machines) != 0 {
		modelInfo.Machines = ModelMachineInfoFromParams(info.Machines)
	}
	if info.SLA != nil {
		modelInfo.SLA = ModelSLAFromParams(info.SLA)
		modelInfo.SLAOwner = ModelSLAOwnerFromParams(info.SLA)
	}

	if info.CloudCredentialTag != "" {
		credTag, err := names.ParseCloudCredentialTag(info.CloudCredentialTag)
		if err != nil {
			return ModelInfo{}, errors.Trace(err)
		}
		modelInfo.Credential = &ModelCredential{
			Name:  credTag.Name(),
			Owner: credTag.Owner().Id(),
			Cloud: credTag.Cloud().Id(),
		}
	}

	return modelInfo, nil
}
1148152
func (p *Parser) Compile() error {
	p.typeMap = make(map[string]map[string]string)
	p.tsMap = make(map[string]map[string]string)
	p.patterns = make(map[string]string)
	p.tsModder = &tsModder{}
	var err error
	p.g, err = grok.NewWithConfig(&grok.Config{NamedCapturesOnly: true})
	if err != nil {
		return err
	}

	if p.UniqueTimestamp == "" {
		p.UniqueTimestamp = "auto"
	}

	// Give Patterns fake names so that they can be treated as named
	// "custom patterns"
	p.NamedPatterns = make([]string, 0, len(p.Patterns))
	for i, pattern := range p.Patterns {
		pattern = strings.TrimSpace(pattern)
		if pattern == "" {
			continue
		}
		name := fmt.Sprintf("GROK_INTERNAL_PATTERN_%d", i)
		p.CustomPatterns += "\n" + name + " " + pattern + "\n"
		p.NamedPatterns = append(p.NamedPatterns, "%{"+name+"}")
	}

	if len(p.NamedPatterns) == 0 {
		return fmt.Errorf("pattern required")
	}

	// Combine user-supplied CustomPatterns with DEFAULT_PATTERNS and parse
	// them together as the same type of pattern.
	p.CustomPatterns = DEFAULT_PATTERNS + p.CustomPatterns
	if len(p.CustomPatterns) != 0 {
		scanner := bufio.NewScanner(strings.NewReader(p.CustomPatterns))
		p.addCustomPatterns(scanner)
	}

	// Parse any custom pattern files supplied.
	for _, filename := range p.CustomPatternFiles {
		file, fileErr := os.Open(filename)
		if fileErr != nil {
			return fileErr
		}

		scanner := bufio.NewScanner(bufio.NewReader(file))
		p.addCustomPatterns(scanner)
	}

	p.loc, err = time.LoadLocation(p.Timezone)
	if err != nil {
		log.Printf("W! improper timezone supplied (%s), setting loc to UTC", p.Timezone)
		p.loc, _ = time.LoadLocation("UTC")
	}

	if p.timeFunc == nil {
		p.timeFunc = time.Now
	}

	return p.compileCustomPatterns()
}
1007681
func (m *MockState) ToApplySpec() applyspec.ApplySpec {
	ret := m.ctrl.Call(m, "ToApplySpec")
	ret0, _ := ret[0].(applyspec.ApplySpec)
	return ret0
}
115577
func MakeCloudSpecGetter(pool Pool) func(names.ModelTag) (environs.CloudSpec, error) {
	return func(tag names.ModelTag) (environs.CloudSpec, error) {
		st, err := pool.Get(tag.Id())
		if err != nil {
			return environs.CloudSpec{}, errors.Trace(err)
		}
		defer st.Release()

		m, err := st.Model()
		if err != nil {
			return environs.CloudSpec{}, errors.Trace(err)
		}
		// TODO - CAAS(externalreality): Once cloud methods are migrated
		// to model EnvironConfigGetter will no longer need to contain
		// both state and model but only model.
		// TODO (manadart 2018-02-15): This potentially frees the state from
		// the pool. Release is called, but the state reference survives.
		return stateenvirons.EnvironConfigGetter{State: st.State, Model: m}.CloudSpec()
	}
}
379090
func (rs RuleSpec) Compile(sm *StateMap) Rule {
	if rs.Include != "" {
		return IncludeRule{
			StateMap:  sm,
			StateName: rs.Include,
		}
	}
	return NewRegexpRule(rs.Regexp, rs.Type, rs.SubTypes,
		strings.Split(rs.State, " "))
}
1241847
func (r *Rego) Compile(ctx context.Context) (*CompileResult, error) {

	pq, err := r.Partial(ctx)
	if err != nil {
		return nil, err
	}

	if len(pq.Support) > 0 {
		return nil, fmt.Errorf("modules not supported")
	}

	policy, err := planner.New().WithQueries(pq.Queries).Plan()
	if err != nil {
		return nil, err
	}

	if r.dump != nil {
		fmt.Fprintln(r.dump, "PLAN:")
		fmt.Fprintln(r.dump, "-----")
		ir.Pretty(r.dump, policy)
		fmt.Fprintln(r.dump)
	}

	m, err := wasm.New().WithPolicy(policy).Compile()
	if err != nil {
		return nil, err
	}

	var out bytes.Buffer

	if err := encoding.WriteModule(&out, m); err != nil {
		return nil, err
	}

	result := &CompileResult{
		Bytes: out.Bytes(),
	}

	return result, nil
}
680968
func (c *modelsCommand) getModelInfo(
	client ModelManagerAPI,
	now time.Time,
	userModels []base.UserModel,
) ([]common.ModelInfo, map[string]jujuclient.ModelDetails, error) {
	tags := make([]names.ModelTag, len(userModels))
	for i, m := range userModels {
		tags[i] = names.NewModelTag(m.UUID)
	}
	results, err := client.ModelInfo(tags)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}

	info := []common.ModelInfo{}
	modelsToStore := map[string]jujuclient.ModelDetails{}
	for i, result := range results {
		if result.Error != nil {
			if params.IsCodeUnauthorized(result.Error) {
				// If we get this, then the model was removed
				// between the initial listing and the call
				// to query its details.
				continue
			}
			return nil, nil, errors.Annotatef(
				result.Error, "getting model %s (%q) info",
				userModels[i].UUID, userModels[i].Name,
			)
		}

		model, err := common.ModelInfoFromParams(*result.Result, now)
		if err != nil {
			return nil, nil, errors.Trace(err)
		}
		model.ControllerName = c.runVars.controllerName
		info = append(info, model)
		modelsToStore[model.Name] = jujuclient.ModelDetails{ModelUUID: model.UUID, ModelType: model.Type}

		if len(model.Machines) != 0 {
			c.runVars.hasMachinesCount = true
			for _, m := range model.Machines {
				if m.Cores != 0 {
					c.runVars.hasCoresCount = true
					break
				}
			}
		}
	}
	return info, modelsToStore, nil
}
124870
func CompileFilter(s string) (*types.Filter, error) {

	es, err := url.QueryUnescape(s)
	if err != nil {
		return nil, err
	}
	s = es

	if len(s) == 0 || s[0] != '(' {
		return nil, errCharZeroNotLParen
	}

	f, pos, err := compileFilter(s, 1)
	if err != nil {
		return nil, err
	}

	if pos != len(s) {
		return nil, goof.WithField(
			"extra", s[pos:],
			"finished compiling filter with extra at end")
	}

	return f, nil
}
1065601
func (mr *MockCompilerMockRecorder) Compile(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Compile", reflect.TypeOf((*MockCompiler)(nil).Compile), arg0)
}
639056
func Compile(expr string, opt RegexOptions) (*Regexp, error) {
	// parse it
	tree, err := syntax.Parse(expr, syntax.RegexOptions(opt))
	if err != nil {
		return nil, err
	}

	// translate it to code
	code, err := syntax.Write(tree)
	if err != nil {
		return nil, err
	}

	// return it
	return &Regexp{
		pattern:      expr,
		options:      opt,
		caps:         code.Caps,
		capnames:     tree.Capnames,
		capslist:     tree.Caplist,
		capsize:      code.Capsize,
		code:         code,
		MatchTimeout: DefaultMatchTimeout,
	}, nil
}
391005
func (c ColumnElem) Compile(d Dialect, params *Parameters) (string, error) {
	var compiled string
	var err error
	if c.inner == nil {
		// Old behavior
		compiled, err = fmt.Sprintf(`"%s"."%s"`, c.table.name, c.name), nil
	} else {
		compiled, err = c.inner.Compile(d, params)
	}
	if err != nil {
		return compiled, err
	}
	if c.alias != "" {
		compiled += fmt.Sprintf(` AS "%s"`, c.alias)
	}
	return compiled, nil
}
1198889
func GenerateSpecWithPlatform(ctx context.Context, client Client, platform string, c *containers.Container, opts ...SpecOpts) (*Spec, error) {
	var s Spec
	if err := generateDefaultSpecWithPlatform(ctx, platform, c.ID, &s); err != nil {
		return nil, err
	}

	return &s, ApplyOpts(ctx, client, c, &s, opts...)
}