resolvers

package
v0.36.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrInternal internalError = "internal error due to a bug or a mishandling of go types AST. This usually indicates a bug in the scanner"
)
View Source
const ExtDeprecated = "x-deprecated"

ExtDeprecated is the vendor-extension key codescan uses to flag a deprecated model or field.

OAS v2 has a native `deprecated` field only on operations; for schemas (models and their fields) the widely-used convention is the `x-deprecated: true` vendor extension. It is NOT an `x-go-*` reflection-metadata extension, so it is emitted regardless of Options.SkipExtensions — it carries author intent, not Go internals.

Detection of the deprecation (explicit `deprecated:` keyword or a godoc "Deprecated:" paragraph) is done in the grammar; builders consume the single grammar.Block.IsDeprecated() signal. See go-swagger/go-swagger#3138.

View Source
const ExtEnumDesc = "x-go-enum-desc"

ExtEnumDesc is the vendor-extension key the scanner uses to expose the per-enum-value documentation lines built from `swagger:enum` + const-block comments. It's a go-swagger concept (not part of the OpenAPI spec); the key lives in `resolvers` so every builder (schema, parameters, responses) reads and writes it through the same constant.

Variables

View Source
var ErrResolver = errors.New("codescan:resolver")

ErrResolver is the sentinel error for all errors originating from the resolver package.

Functions

func AddExtension

func AddExtension(ve *oaispec.VendorExtensible, key string, value any, skip bool)

func AppendEnumDesc added in v0.35.0

func AppendEnumDesc(description string, extensions oaispec.Extensions, skip bool) string

AppendEnumDesc folds the x-go-enum-desc const-name mapping (if any) into description, returning the resulting description.

A newline separates the authored prose from the appended mapping.

When skip is true the description is returned unchanged — the mapping then rides x-go-enum-desc only.

This is the single gate shared by the schema (model decl + struct field) and parameter builders so the SkipEnumDescriptions option behaves identically across every target that folds the mapping in.

Response headers never fold the mapping into their description, so they don't call this — but they do carry it on x-go-enum-desc in both modes (spec >= v0.22.6 marshals header vendor extensions). See go-swagger/go-swagger#2922.

func ExplicitJSONName added in v0.35.0

func ExplicitJSONName(field *ast.Field) string

ExplicitJSONName returns the name set in a field's json struct tag — the part before the first comma — or "" when the field has no json tag, the tag sets no name (`json:",omitempty"`), or the tag skips the field (`json:"-"`).

Go's encoding/json treats an *embedded* struct field carrying an explicit json name as a regular named field: the embedded value nests under that name instead of being promoted. Callers use a non-empty result to distinguish a nesting embed from a flattening one (go-swagger#2038).

func FindASTFieldFor added in v0.36.4

func FindASTFieldFor(file *ast.File, obj types.Object, posOf func(token.Pos) token.Position) *ast.Field

FindASTFieldFor returns the struct field or interface method declaring obj in file, or nil when there is none.

Position first, and for a package read from source that is the whole story: the object and the syntax came out of the same type-check, so obj.Pos() indexes straight into file.

A package whose types were read from compiled export data and whose source was parsed separately is the case the name fallback exists for.

The two halves reach the same FileSet by different routes and get a token.File each, so the same declaration holds two unrelated token.Pos values and the position lookup finds nothing at all. Without the fallback every field of such a type is silently skipped, which renders the type as an empty object rather than failing.

Export data preserves the filename and the LINE, not the column. The importer fabricates a line table in which every position sits in column 1, so a column comparison is always wrong.

Line plus the object's own name identifies the field, since a struct cannot declare a name twice and the file is already known.

NOTE: the pathological miss is two types declaring the same field name on one physical line, which costs one field the prose from the other.

Reached only when the position lookup fails, so an ordinary scan never walks the file twice.

func GetEnumDesc added in v0.34.1

func GetEnumDesc(extensions oaispec.Extensions) string

GetEnumDesc reads the x-go-enum-desc extension off a Swagger extensions map.

Empty when absent.

Consumers typically check this after a build pass to know whether they should append the per-value docs to a Description (parameters do this for the parameter description; the schema builder folds it in differently — see `handlers/dispatch_schema.go:clearStaleEnumDesc` for the override-cleanup dance).

Response headers carry the mapping on x-go-enum-desc but never fold it into the header description.

func IsAny

func IsAny(o *types.TypeName) bool

func IsFieldStringable

func IsFieldStringable(tpe ast.Expr) bool

IsFieldStringable check if the field type is a scalar.

If the field type is *ast.StarExpr and is pointer type, check if it refers to a scalar. Otherwise, the ",string" directive doesn't apply.

func IsJSONMapKey added in v0.35.0

func IsJSONMapKey(key types.Type) bool

IsJSONMapKey reports whether a Go map with this key type marshals to a JSON object under encoding/json — i.e. whether the map is representable as {type: object, additionalProperties: V}.

The rule mirrors encoding/json's newMapEncoder: the key kind is string or any integer / unsigned-integer kind (int, int8…int64, uint, uint8…uint64, uintptr — all stringified), or the key implements encoding.TextMarshaler.

Everything else (float, bool, struct without TextMarshaler, interface, func) makes json.Marshal fail; json.Marshaler is never consulted for keys.

func IsOpaqueStream added in v0.36.3

func IsOpaqueStream(o *types.TypeName) bool

IsOpaqueStream reports whether o is one of the known byte-stream carriers.

Identity-based, so it answers from the object alone and can run ahead of any declaration lookup — which matters, because the drilling these types used to reach invented a `close` property of type string out of `Close() error`.

func IsStdBigFloat added in v0.36.4

func IsStdBigFloat(o *types.TypeName) bool

IsStdBigFloat reports whether o is math/big.Float, which travels as a JSON *string* holding a decimal float ("3.5"): it has MarshalText and no MarshalJSON, and unmarshalling rejects a number.

func IsStdBigInt added in v0.36.4

func IsStdBigInt(o *types.TypeName) bool

IsStdBigInt reports whether o is math/big.Int, which travels as a JSON *number*: it carries a MarshalJSON emitting a bare numeric literal, and encoding/json prefers json.Marshaler over the MarshalText the same type also has.

func IsStdBigRat added in v0.36.4

func IsStdBigRat(o *types.TypeName) bool

IsStdBigRat reports whether o is math/big.Rat, which travels as a JSON *string* holding a quotient ("5/3"): it has MarshalText and no MarshalJSON, and unmarshalling rejects a number.

func IsStdError

func IsStdError(o *types.TypeName) bool

func IsStdErrorType added in v0.36.3

func IsStdErrorType(t types.Type) bool

IsStdErrorType reports whether t IS the predeclared error, however it is spelled.

IsStdError keys on an object, and an alias's object is the alias's own name — so `type Wrapped = error` never matches it, and a rule written against the object alone applies to one spelling of the same type and not the other.

func IsStdJSONRawMessage

func IsStdJSONRawMessage(o *types.TypeName) bool

IsStdJSONRawMessage reports whether o is encoding/json.RawMessage, in either of the two shapes a toolchain gives it.

go1.27 turned RawMessage into an alias of encoding/json/jsontext.Value, so unaliasing a field written as json.RawMessage now lands on jsontext.Value, and a predicate that reads only (encoding/json, RawMessage) stopped matching there: the type fell through to its []byte underlying and rendered as an array of uint8 instead of "any JSON". Both names mean raw JSON text, so both answer yes.

func IsStdTime

func IsStdTime(o *types.TypeName) bool

func IsStdUUID added in v0.36.2

func IsStdUUID(o *types.TypeName) bool

IsStdUUID reports whether o is the go1.27 stdlib uuid.UUID.

Identity-based, so it never misfires on the many third-party types also named UUID (github.com/google/uuid, gofrs, strfmt, …) — those keep going through the fuzzy name heuristic in the schema builder.

Deliberately NOT behind a go1.27 build tag: codescan compares types harvested from *scanned* code, never imports uuid itself, and ships as a binary that may be built by an older toolchain than the module it scans.

func IsTextMarshaler

func IsTextMarshaler(tpe types.Type) bool

func MarkDeprecated added in v0.35.0

func MarkDeprecated(ps *oaispec.Schema)

MarkDeprecated sets `x-deprecated: true` on the schema.

Idempotent.

func MustHaveRightHandSide

func MustHaveRightHandSide(a *types.Alias)

func MustNotBeABuiltinType

func MustNotBeABuiltinType(o *types.TypeName)

func ParseFieldTag added in v0.35.1

func ParseFieldTag(field *ast.Field, goName string, nameTags []string) (name string, ignore, isString, omitEmpty bool, err error)

ParseFieldTag derives the emitted name and the encoding/json directives for a struct field.

The name is sourced from the first struct-tag type in nameTags that supplies a usable name — a non-empty name-part that isn't "-"; a tag type that is absent or carries only options (e.g. `,omitempty`) is skipped and the next type is tried. nameTags is typically Options.NameFromTags, defaulting to ["json"].

When nameTags is empty, or none of the listed tags name the field, the name falls back to goName — the field's Go identifier as reported by go/types, authoritative because a single AST field group may declare several names (`R, G, B, A uint8`), each a distinct go/types field promoted to its own property (go-swagger#2638).

When goName is empty the first AST name is used.

The `-` (ignore), `,omitempty` and `,string` directives are ALWAYS read from the `json` tag, independent of nameTags — they describe the encoding/json wire shape, not the Swagger name. `json:"-"` ignores the field.

A rename can only name a single field, so it is dropped for a multi-name group — each member keeps its own Go name — while the directives still apply to every member.

func SwaggerSchemaForType

func SwaggerSchemaForType(typeName string, prop ifaces.SwaggerTypable) error

SwaggerSchemaForType maps all Go builtin types that have Json representation to Swagger/Json types.

See https://golang.org/pkg/builtin/ and http://swagger.io/specification/.

func UnsupportedBasic

func UnsupportedBasic(tpe *types.Basic) bool

func UnsupportedBuiltin

func UnsupportedBuiltin(tpe ifaces.Objecter) (skip bool)

UnsupportedBuiltin returns true when tpe is unsafe.Pointer.

Other "unsupported builtins" (complex64, complex128) cannot reach this function: they surface as *types.Basic, which does not satisfy ifaces.Objecter. Those are caught one layer down by UnsupportedBasic / UnsupportedBuiltinType when the *types.Basic surfaces directly.

Supported builtins:

  • error

func UnsupportedBuiltinType

func UnsupportedBuiltinType(tpe types.Type) bool

Types

type Embed added in v0.36.4

type Embed struct {
	Field *ast.Field
	Type  types.Type
}

Embed pairs an anonymous entry of a declaration's member list with the type go/types gave it.

The AST half carries the annotation — an embed's `swagger:allOf` / `swagger:ignore` lives in its doc comment and nowhere else — and the type half gives what the embed denotes.

func Embeds added in v0.36.4

func Embeds(members []*ast.Field, under types.Type) []Embed

Embeds pairs every anonymous member of an AST member list with its type, read from the declared type's underlying rather than from types.Info.

members is a struct's field list or an interface's method list, and under the same declaration's underlying type. The pairing is positional, which is exact in both shapes:

  • a struct's fields are built in source order, an entry with N names contributing N fields and an anonymous one contributing exactly one embedded field;
  • an interface's embedded types are recorded in source order, so the k-th anonymous member is the k-th embedded type.

Entries the two halves do not agree on are dropped rather than guessed at. Anything that is neither a struct nor an interface has no embeds and yields nothing.

Reading the underlying type instead of types.Info.Types resolves an embed for a package whose types were not checked from its source — export data carries the struct and its field types, and carries no expression records at all.

type ItemsTypable added in v0.34.1

type ItemsTypable struct {
	// contains filtered or unexported fields
}

ItemsTypable adapts an *oaispec.Items target to ifaces.SwaggerTypable so the parameters/responses builders can recurse through nested array layers (SimpleSchema's items chain).

One adapter, two callers (parameters, responses); lives here because it's pure ifaces-glue with no builder-specific logic. The schema builder uses its own *oaispec.Schema.Items chain and has no need for this adapter.

func NewItemsTypable added in v0.34.1

func NewItemsTypable(items *oaispec.Items, level int, in string) ItemsTypable

func (ItemsTypable) AddExtension added in v0.34.1

func (pt ItemsTypable) AddExtension(key string, value any)

func (ItemsTypable) HasRef added in v0.35.0

func (pt ItemsTypable) HasRef() bool

HasRef satisfies schema.SimpleSchemaProbe.

SimpleSchema forbids a $ref, including on array items: a named object element ([]Ele under in: query) otherwise resolves to `items: {$ref}`, which the Swagger 2.0 editor rejects (go-swagger#1088).

func (ItemsTypable) In added in v0.34.1

func (pt ItemsTypable) In() string

func (ItemsTypable) Items added in v0.34.1

func (pt ItemsTypable) Items() ifaces.SwaggerTypable

func (ItemsTypable) Level added in v0.34.1

func (pt ItemsTypable) Level() int

func (ItemsTypable) ResetForViolation added in v0.35.0

func (pt ItemsTypable) ResetForViolation()

ResetForViolation satisfies schema.SimpleSchemaProbe.

Dissolves an illegal $ref / shape on this items level back to empty, mirroring paramTypable.ResetForViolation one level down.

func (ItemsTypable) Schema added in v0.34.1

func (pt ItemsTypable) Schema() *oaispec.Schema

func (ItemsTypable) SetRef added in v0.34.1

func (pt ItemsTypable) SetRef(ref oaispec.Ref)

func (ItemsTypable) SimpleSchemaShape added in v0.35.0

func (pt ItemsTypable) SimpleSchemaShape() *oaispec.SimpleSchema

SimpleSchemaShape satisfies schema.SimpleSchemaProbe: an items level in a non-body parameter / response header is itself a Swagger 2.0 SimpleSchema.

Exposing it lets the schema builder's catch-at-exit validator inspect array-element shapes, not just the top-level target (go-swagger#1088).

func (ItemsTypable) Typed added in v0.34.1

func (pt ItemsTypable) Typed(tpe, format string)

func (ItemsTypable) WithEnum added in v0.34.1

func (pt ItemsTypable) WithEnum(values ...any)

func (ItemsTypable) WithEnumDescription added in v0.34.1

func (pt ItemsTypable) WithEnumDescription(_ string)

type ItemsValidations added in v0.34.1

type ItemsValidations struct {
	// contains filtered or unexported fields
}

ItemsValidations wraps an *oaispec.Items as a ValidationBuilder / OperationValidationBuilder target.

Used by parameters' and responses' grammar items-level Walker dispatch.

func NewItemsValidations added in v0.34.1

func NewItemsValidations(it *oaispec.Items) ItemsValidations

func (ItemsValidations) SetCollectionFormat added in v0.34.1

func (sv ItemsValidations) SetCollectionFormat(val string)

func (ItemsValidations) SetDefault added in v0.34.1

func (sv ItemsValidations) SetDefault(val any)

func (ItemsValidations) SetEnum added in v0.34.1

func (sv ItemsValidations) SetEnum(val string)

func (ItemsValidations) SetExample added in v0.34.1

func (sv ItemsValidations) SetExample(val any)

func (ItemsValidations) SetMaxItems added in v0.34.1

func (sv ItemsValidations) SetMaxItems(val int64)

func (ItemsValidations) SetMaxLength added in v0.34.1

func (sv ItemsValidations) SetMaxLength(val int64)

func (ItemsValidations) SetMaximum added in v0.34.1

func (sv ItemsValidations) SetMaximum(val float64, exclusive bool)

func (ItemsValidations) SetMinItems added in v0.34.1

func (sv ItemsValidations) SetMinItems(val int64)

func (ItemsValidations) SetMinLength added in v0.34.1

func (sv ItemsValidations) SetMinLength(val int64)

func (ItemsValidations) SetMinimum added in v0.34.1

func (sv ItemsValidations) SetMinimum(val float64, exclusive bool)

func (ItemsValidations) SetMultipleOf added in v0.34.1

func (sv ItemsValidations) SetMultipleOf(val float64)

func (ItemsValidations) SetPattern added in v0.34.1

func (sv ItemsValidations) SetPattern(val string)

func (ItemsValidations) SetUnique added in v0.34.1

func (sv ItemsValidations) SetUnique(val bool)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL