tagparser

package
v0.11.7 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package tagparser parses struct-tag validation rules into a reusable representation shared by GoZod runtime code and codegen.

Callers should prefer FieldInfo helper methods such as FieldInfo.ValidationRules, FieldInfo.NeedsGeneratedOptional, and FieldInfo.RequiredImports instead of re-deriving schema-generation semantics from raw fields like Rules, Required, or Optional.

Use TagParser.ParseStructTags for compatibility-oriented callers that prefer empty results on non-struct input, or TagParser.ParseStructTagsStrict when non-struct input should be treated as a contract error.

A parser is configured with two tag names: the rule tag (default "gozod") and the field-name tag that supplies field names (default "json"). Use NewWithTags to select both, or FieldName to resolve a single field's name from a chosen field-name tag such as "yaml" or "toml".

Package tagparser provides shared tag parsing functionality for GoZod. Extracted from types/struct.go to enable reuse by cmd/gozodgen and other components.

Index

Constants

This section is empty.

Variables

View Source
var ErrEmptyRuleName = errors.New("tagparser: empty rule name")

ErrEmptyRuleName indicates that a tag rule has no rule name.

View Source
var ErrRuleRequiresParam = errors.New("tagparser: rule requires a parameter")

ErrRuleRequiresParam indicates that a tag rule used "=" without a value.

View Source
var ErrTypeMustBeStruct = errors.New("tagparser: type must be a struct or pointer to struct")

ErrTypeMustBeStruct indicates that the input type is neither a struct nor a pointer to struct.

Functions

This section is empty.

Types

type FieldInfo

type FieldInfo struct {
	Name     string       // Go field name
	Type     reflect.Type // field type
	TypeName string       // AST type name for circular reference detection
	FieldKey string       // from the field-name tag, or Go field name
	GoZodTag string       // raw gozod tag value
	Rules    []TagRule    // parsed tag rules before helper-level filtering
	Required bool         // whether the parsed rules include "required"
	Optional bool         // derived optionality for parsed-tag callers
	Nilable  bool         // whether the parsed rules include "nilable"
}

FieldInfo represents parsed information about a struct field.

func (FieldInfo) EffectiveTypeName added in v0.10.0

func (f FieldInfo) EffectiveTypeName() string

EffectiveTypeName returns the best available type name for codegen.

func (FieldInfo) EnumRule added in v0.10.0

func (f FieldInfo) EnumRule() *TagRule

EnumRule returns the enum rule if present.

func (FieldInfo) HasCoerceRule added in v0.10.0

func (f FieldInfo) HasCoerceRule() bool

HasCoerceRule reports whether the field enables coercion.

func (FieldInfo) HasRule added in v0.10.0

func (f FieldInfo) HasRule(name string) bool

HasRule reports whether a parsed rule with the given name exists.

func (FieldInfo) HasRules added in v0.10.0

func (f FieldInfo) HasRules() bool

HasRules reports whether the field has any parsed tag rules.

func (FieldInfo) HasSchemaSpec added in v0.10.0

func (f FieldInfo) HasSchemaSpec() bool

HasSchemaSpec reports whether the field has tag-derived schema semantics. Runtime/codegen consumers should prefer helper methods on FieldInfo instead of open-coding logic from the raw fields.

func (FieldInfo) IsEnumStringField added in v0.10.0

func (f FieldInfo) IsEnumStringField() bool

IsEnumStringField reports whether this field should use the Enum constructor.

func (FieldInfo) IsPointerType added in v0.10.0

func (f FieldInfo) IsPointerType() bool

IsPointerType reports whether the field type is a pointer.

func (FieldInfo) IsUUIDStringField added in v0.10.0

func (f FieldInfo) IsUUIDStringField() bool

IsUUIDStringField reports whether this field should use the UUID constructor.

func (FieldInfo) NeedsCoreImport added in v0.10.0

func (f FieldInfo) NeedsCoreImport() bool

NeedsCoreImport reports whether codegen should import core.

func (FieldInfo) NeedsGeneratedOptional added in v0.10.0

func (f FieldInfo) NeedsGeneratedOptional() bool

NeedsGeneratedOptional reports whether generated schema code should append .Optional() after applying all rules.

func (FieldInfo) NeedsNetImport added in v0.10.0

func (f FieldInfo) NeedsNetImport() bool

NeedsNetImport reports whether codegen should import net. IP tags generate root GoZod constructors and do not need net.

func (FieldInfo) NeedsNetURLImport added in v0.10.0

func (f FieldInfo) NeedsNetURLImport() bool

NeedsNetURLImport reports whether codegen should import net/url. URL tags generate root GoZod constructors and do not need net/url.

func (FieldInfo) NeedsOptionalModifier added in v0.10.0

func (f FieldInfo) NeedsOptionalModifier() bool

NeedsOptionalModifier reports whether generated schema code should append .Optional() for this field.

func (FieldInfo) NeedsPointerNilable added in v0.10.0

func (f FieldInfo) NeedsPointerNilable() bool

NeedsPointerNilable reports whether a pointer-backed schema should become nilable during struct-schema derivation.

func (FieldInfo) NeedsPointerOptional added in v0.10.0

func (f FieldInfo) NeedsPointerOptional() bool

NeedsPointerOptional reports whether pointer field rules should add Optional() at the end of parsed tag application.

func (FieldInfo) NeedsRegexpImport added in v0.10.0

func (f FieldInfo) NeedsRegexpImport() bool

NeedsRegexpImport reports whether codegen should import regexp.

func (FieldInfo) NeedsStringsImport added in v0.10.0

func (f FieldInfo) NeedsStringsImport() bool

NeedsStringsImport reports whether codegen should import strings.

func (FieldInfo) RequiredImports added in v0.10.0

func (f FieldInfo) RequiredImports() []string

RequiredImports returns the non-gozod imports needed to generate this field.

func (FieldInfo) RulesExcept added in v0.10.0

func (f FieldInfo) RulesExcept(names ...string) []TagRule

RulesExcept returns all parsed rules except those whose names are excluded.

func (FieldInfo) UsesTimeImport added in v0.10.0

func (f FieldInfo) UsesTimeImport() bool

UsesTimeImport reports whether codegen should import time for this field.

func (FieldInfo) ValidationRules added in v0.10.0

func (f FieldInfo) ValidationRules() []TagRule

ValidationRules returns tag rules that should become schema modifiers or checks at runtime/codegen. Structural rules are handled elsewhere.

func (FieldInfo) ValidationRulesExcept added in v0.10.0

func (f FieldInfo) ValidationRulesExcept(names ...string) []TagRule

ValidationRulesExcept returns validation rules except those explicitly excluded.

type FieldNameResult added in v0.11.6

type FieldNameResult struct {
	Name string
	Skip bool
}

FieldNameResult represents the resolved schema key for a struct field.

func FieldName added in v0.11.6

func FieldName(tagName string, f reflect.StructField) FieldNameResult

FieldName resolves the field name and skip marker for a struct field using the named struct tag (e.g. "json", "yaml", "toml"). An absent tag falls back to the Go field name; a tag value of "-" marks the field as skipped.

type FieldPlan added in v0.11.7

type FieldPlan struct {
	Operations             []RulePlan
	RuntimePointerOptional OptionalPlacement
	GeneratedOptional      OptionalPlacement
}

FieldPlan is the shared semantic plan for a parsed struct field.

func CompileFieldPlan added in v0.11.7

func CompileFieldPlan(field *FieldInfo) FieldPlan

CompileFieldPlan converts parsed field facts into semantic operations shared by runtime reflection and code generation.

func (FieldPlan) OperationsExcept added in v0.11.7

func (p FieldPlan) OperationsExcept(names ...string) []RulePlan

OperationsExcept returns planned operations except those for the named raw rules.

type OptionalPlacement added in v0.11.7

type OptionalPlacement string

OptionalPlacement describes where an Optional modifier belongs relative to field operations when a backend must express optionality as a fluent call.

const (
	// OptionalPlacementNone means no generated Optional modifier is needed.
	OptionalPlacementNone OptionalPlacement = "none"
	// OptionalPlacementBeforeOperations places Optional before planned rule operations.
	OptionalPlacementBeforeOperations OptionalPlacement = "before_operations"
	// OptionalPlacementAfterOperations places Optional after planned rule operations.
	OptionalPlacementAfterOperations OptionalPlacement = "after_operations"
)

type RuleOp added in v0.11.5

type RuleOp string

RuleOp identifies the semantic operation represented by a tag rule.

const (
	RuleStructural  RuleOp = "structural"
	RuleMethod      RuleOp = "method"
	RuleStringCheck RuleOp = "string_check"
	RuleTime        RuleOp = "time"
	RulePositive    RuleOp = "positive"
	RuleNegative    RuleOp = "negative"
	RuleFinite      RuleOp = "finite"
	RuleNonEmpty    RuleOp = "nonempty"
	RuleEnum        RuleOp = "enum"
	RuleLiteral     RuleOp = "literal"
	RuleDefault     RuleOp = "default"
	RulePrefault    RuleOp = "prefault"
	RuleUnsupported RuleOp = "unsupported"
)

RuleOp values describe shared tag-rule operations.

type RulePlan added in v0.11.5

type RulePlan struct {
	Rule   TagRule
	Op     RuleOp
	Method string
}

RulePlan is the shared semantic plan for a parsed tag rule.

func CompileRule added in v0.11.5

func CompileRule(rule TagRule) RulePlan

CompileRule converts a parsed tag rule into a shared semantic plan.

func (RulePlan) FirstParam added in v0.11.5

func (p RulePlan) FirstParam() (string, bool)

FirstParam returns the first parameter for rules that take one argument.

func (RulePlan) JoinedValue added in v0.11.5

func (p RulePlan) JoinedValue() (string, bool)

JoinedValue returns a single value for default-like rules.

type TagParser

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

TagParser handles gozod tag parsing with configurable tag names. rulesTagName selects the rule tag (default "gozod"); fieldNameTag selects the tag that supplies field names (default "json").

func New

func New() *TagParser

New creates a TagParser with the default "gozod" rule tag and "json" field-name tag.

func NewWithTagName

func NewWithTagName(name string) *TagParser

NewWithTagName creates a TagParser with a custom rule tag and the default "json" field-name tag.

func NewWithTags added in v0.11.6

func NewWithTags(ruleTag, fieldNameTag string) *TagParser

NewWithTags creates a TagParser with custom rule and field-name tags. Empty values fall back to the defaults ("gozod" and "json").

func (*TagParser) ParseStructTags

func (p *TagParser) ParseStructTags(typ reflect.Type) ([]FieldInfo, error)

ParseStructTags parses all gozod tags in a struct type and returns FieldInfo for each exported field.

Non-struct input returns an empty slice and no error. Use [ParseStructTagsStrict] when non-struct input should fail.

func (*TagParser) ParseStructTagsStrict added in v0.10.0

func (p *TagParser) ParseStructTagsStrict(typ reflect.Type) ([]FieldInfo, error)

ParseStructTagsStrict parses all gozod tags in a struct type and returns ErrTypeMustBeStruct for non-struct input.

func (*TagParser) ParseTagString

func (p *TagParser) ParseTagString(tag string) ([]TagRule, error)

ParseTagString parses a single tag string into TagRule values.

type TagRule

type TagRule struct {
	Name   string   // e.g., "min", "max", "email"
	Params []string // e.g., ["2"] for "min=2"
}

TagRule represents a single validation rule parsed from a tag.

Jump to

Keyboard shortcuts

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