Documentation
¶
Overview ¶
Package grammar is the annotation parser for codescan. It consumes one Go comment group at a time, recognises the swagger:<name> annotation header, and produces a typed Block carrying:
- the recognised annotation as an AnnotationKind;
- per-Block fields for the annotation's positional arguments;
- Property entries for every recognised body keyword;
- prose lines split into Title() / Description();
- diagnostics for malformed inputs (the parser never aborts).
Pipeline:
*ast.CommentGroup
│
▼
Preprocess → []Line (comment-marker stripping)
│
▼
Lex → []Token (line classifier + body accumulator + prose classifier)
│
▼
Parse → Block (dispatch by annotation family)
The Token vocabulary is defined in token.go.
Details ¶
See README.md in this package for the full contract: pipeline stages, lexer / parser rules, keyword table, walker dispatch table, body-termination rules, diagnostics codes, and known follow-ups.
Index ¶
- Constants
- func FormatToken(t Token) string
- func NormalizeIn(raw string, allowFormAlias bool) (string, bool)
- type AnnotationKind
- type Block
- type ClassifierBlock
- func (b *ClassifierBlock) AnnotationArg() (string, bool)
- func (b ClassifierBlock) AnnotationKind() AnnotationKind
- func (b ClassifierBlock) Contact() (Contact, error)
- func (b ClassifierBlock) Description() string
- func (b ClassifierBlock) Diagnostics() []Diagnostic
- func (b ClassifierBlock) Extensions() iter.Seq[Extension]
- func (b ClassifierBlock) GetBool(name string) (bool, bool)
- func (b ClassifierBlock) GetFloat(name string) (float64, bool)
- func (b ClassifierBlock) GetInt(name string) (int64, bool)
- func (b ClassifierBlock) GetList(name string) ([]string, bool)
- func (b ClassifierBlock) GetString(name string) (string, bool)
- func (b ClassifierBlock) Has(name string) bool
- func (b ClassifierBlock) License() (License, bool)
- func (b ClassifierBlock) Pos() token.Position
- func (b ClassifierBlock) PreambleDescription() string
- func (b ClassifierBlock) PreambleLines() []string
- func (b ClassifierBlock) PreambleTitle() string
- func (b ClassifierBlock) Properties() iter.Seq[Property]
- func (b ClassifierBlock) Prose() string
- func (b ClassifierBlock) ProseLines() []string
- func (b ClassifierBlock) SecurityRequirements() []security.Requirement
- func (b ClassifierBlock) Title() string
- func (b ClassifierBlock) Walk(w Walker)
- func (b ClassifierBlock) YAMLBlocks() iter.Seq[RawYAML]
- type Code
- type Contact
- type DefaultParser
- type Diagnostic
- type EnumDeclBlock
- func (b *EnumDeclBlock) AnnotationArg() (string, bool)
- func (b EnumDeclBlock) AnnotationKind() AnnotationKind
- func (b EnumDeclBlock) Contact() (Contact, error)
- func (b EnumDeclBlock) Description() string
- func (b EnumDeclBlock) Diagnostics() []Diagnostic
- func (b EnumDeclBlock) Extensions() iter.Seq[Extension]
- func (b EnumDeclBlock) GetBool(name string) (bool, bool)
- func (b EnumDeclBlock) GetFloat(name string) (float64, bool)
- func (b EnumDeclBlock) GetInt(name string) (int64, bool)
- func (b EnumDeclBlock) GetList(name string) ([]string, bool)
- func (b EnumDeclBlock) GetString(name string) (string, bool)
- func (b EnumDeclBlock) Has(name string) bool
- func (b EnumDeclBlock) License() (License, bool)
- func (b EnumDeclBlock) Pos() token.Position
- func (b EnumDeclBlock) PreambleDescription() string
- func (b EnumDeclBlock) PreambleLines() []string
- func (b EnumDeclBlock) PreambleTitle() string
- func (b EnumDeclBlock) Properties() iter.Seq[Property]
- func (b EnumDeclBlock) Prose() string
- func (b EnumDeclBlock) ProseLines() []string
- func (b EnumDeclBlock) SecurityRequirements() []security.Requirement
- func (b EnumDeclBlock) Title() string
- func (b EnumDeclBlock) Walk(w Walker)
- func (b EnumDeclBlock) YAMLBlocks() iter.Seq[RawYAML]
- type Extension
- type InlineOperationBlock
- func (b InlineOperationBlock) AnnotationArg() (string, bool)
- func (b InlineOperationBlock) AnnotationKind() AnnotationKind
- func (b InlineOperationBlock) Contact() (Contact, error)
- func (b InlineOperationBlock) Description() string
- func (b InlineOperationBlock) Diagnostics() []Diagnostic
- func (b InlineOperationBlock) Extensions() iter.Seq[Extension]
- func (b InlineOperationBlock) GetBool(name string) (bool, bool)
- func (b InlineOperationBlock) GetFloat(name string) (float64, bool)
- func (b InlineOperationBlock) GetInt(name string) (int64, bool)
- func (b InlineOperationBlock) GetList(name string) ([]string, bool)
- func (b InlineOperationBlock) GetString(name string) (string, bool)
- func (b InlineOperationBlock) Has(name string) bool
- func (b InlineOperationBlock) License() (License, bool)
- func (b InlineOperationBlock) Pos() token.Position
- func (b InlineOperationBlock) PreambleDescription() string
- func (b InlineOperationBlock) PreambleLines() []string
- func (b InlineOperationBlock) PreambleTitle() string
- func (b InlineOperationBlock) Properties() iter.Seq[Property]
- func (b InlineOperationBlock) Prose() string
- func (b InlineOperationBlock) ProseLines() []string
- func (b InlineOperationBlock) SecurityRequirements() []security.Requirement
- func (b InlineOperationBlock) Title() string
- func (b InlineOperationBlock) Walk(w Walker)
- func (b InlineOperationBlock) YAMLBlocks() iter.Seq[RawYAML]
- type Keyword
- type KeywordContext
- type License
- type Line
- type MetaBlock
- func (b MetaBlock) AnnotationArg() (string, bool)
- func (b MetaBlock) AnnotationKind() AnnotationKind
- func (b MetaBlock) Contact() (Contact, error)
- func (b MetaBlock) Description() string
- func (b MetaBlock) Diagnostics() []Diagnostic
- func (b MetaBlock) Extensions() iter.Seq[Extension]
- func (b MetaBlock) GetBool(name string) (bool, bool)
- func (b MetaBlock) GetFloat(name string) (float64, bool)
- func (b MetaBlock) GetInt(name string) (int64, bool)
- func (b MetaBlock) GetList(name string) ([]string, bool)
- func (b MetaBlock) GetString(name string) (string, bool)
- func (b MetaBlock) Has(name string) bool
- func (b MetaBlock) License() (License, bool)
- func (b MetaBlock) Pos() token.Position
- func (b MetaBlock) PreambleDescription() string
- func (b MetaBlock) PreambleLines() []string
- func (b MetaBlock) PreambleTitle() string
- func (b MetaBlock) Properties() iter.Seq[Property]
- func (b MetaBlock) Prose() string
- func (b MetaBlock) ProseLines() []string
- func (b MetaBlock) SecurityRequirements() []security.Requirement
- func (b MetaBlock) Title() string
- func (b MetaBlock) Walk(w Walker)
- func (b MetaBlock) YAMLBlocks() iter.Seq[RawYAML]
- type ModelBlock
- func (b *ModelBlock) AnnotationArg() (string, bool)
- func (b ModelBlock) AnnotationKind() AnnotationKind
- func (b ModelBlock) Contact() (Contact, error)
- func (b ModelBlock) Description() string
- func (b ModelBlock) Diagnostics() []Diagnostic
- func (b ModelBlock) Extensions() iter.Seq[Extension]
- func (b ModelBlock) GetBool(name string) (bool, bool)
- func (b ModelBlock) GetFloat(name string) (float64, bool)
- func (b ModelBlock) GetInt(name string) (int64, bool)
- func (b ModelBlock) GetList(name string) ([]string, bool)
- func (b ModelBlock) GetString(name string) (string, bool)
- func (b ModelBlock) Has(name string) bool
- func (b ModelBlock) License() (License, bool)
- func (b ModelBlock) Pos() token.Position
- func (b ModelBlock) PreambleDescription() string
- func (b ModelBlock) PreambleLines() []string
- func (b ModelBlock) PreambleTitle() string
- func (b ModelBlock) Properties() iter.Seq[Property]
- func (b ModelBlock) Prose() string
- func (b ModelBlock) ProseLines() []string
- func (b ModelBlock) SecurityRequirements() []security.Requirement
- func (b ModelBlock) Title() string
- func (b ModelBlock) Walk(w Walker)
- func (b ModelBlock) YAMLBlocks() iter.Seq[RawYAML]
- type NameBlock
- func (b *NameBlock) AnnotationArg() (string, bool)
- func (b NameBlock) AnnotationKind() AnnotationKind
- func (b NameBlock) Contact() (Contact, error)
- func (b NameBlock) Description() string
- func (b NameBlock) Diagnostics() []Diagnostic
- func (b NameBlock) Extensions() iter.Seq[Extension]
- func (b NameBlock) GetBool(name string) (bool, bool)
- func (b NameBlock) GetFloat(name string) (float64, bool)
- func (b NameBlock) GetInt(name string) (int64, bool)
- func (b NameBlock) GetList(name string) ([]string, bool)
- func (b NameBlock) GetString(name string) (string, bool)
- func (b NameBlock) Has(name string) bool
- func (b NameBlock) License() (License, bool)
- func (b NameBlock) Pos() token.Position
- func (b NameBlock) PreambleDescription() string
- func (b NameBlock) PreambleLines() []string
- func (b NameBlock) PreambleTitle() string
- func (b NameBlock) Properties() iter.Seq[Property]
- func (b NameBlock) Prose() string
- func (b NameBlock) ProseLines() []string
- func (b NameBlock) SecurityRequirements() []security.Requirement
- func (b NameBlock) Title() string
- func (b NameBlock) Walk(w Walker)
- func (b NameBlock) YAMLBlocks() iter.Seq[RawYAML]
- type Option
- type ParametersBlock
- func (b ParametersBlock) AnnotationArg() (string, bool)
- func (b ParametersBlock) AnnotationKind() AnnotationKind
- func (b ParametersBlock) Contact() (Contact, error)
- func (b ParametersBlock) Description() string
- func (b ParametersBlock) Diagnostics() []Diagnostic
- func (b ParametersBlock) Extensions() iter.Seq[Extension]
- func (b ParametersBlock) GetBool(name string) (bool, bool)
- func (b ParametersBlock) GetFloat(name string) (float64, bool)
- func (b ParametersBlock) GetInt(name string) (int64, bool)
- func (b ParametersBlock) GetList(name string) ([]string, bool)
- func (b ParametersBlock) GetString(name string) (string, bool)
- func (b ParametersBlock) Has(name string) bool
- func (b ParametersBlock) License() (License, bool)
- func (b ParametersBlock) Pos() token.Position
- func (b ParametersBlock) PreambleDescription() string
- func (b ParametersBlock) PreambleLines() []string
- func (b ParametersBlock) PreambleTitle() string
- func (b ParametersBlock) Properties() iter.Seq[Property]
- func (b ParametersBlock) Prose() string
- func (b ParametersBlock) ProseLines() []string
- func (b ParametersBlock) SecurityRequirements() []security.Requirement
- func (b ParametersBlock) Title() string
- func (b ParametersBlock) Walk(w Walker)
- func (b ParametersBlock) YAMLBlocks() iter.Seq[RawYAML]
- type Parser
- type Property
- type RawYAML
- type ResponseBlock
- func (b *ResponseBlock) AnnotationArg() (string, bool)
- func (b ResponseBlock) AnnotationKind() AnnotationKind
- func (b ResponseBlock) Contact() (Contact, error)
- func (b ResponseBlock) Description() string
- func (b ResponseBlock) Diagnostics() []Diagnostic
- func (b ResponseBlock) Extensions() iter.Seq[Extension]
- func (b ResponseBlock) GetBool(name string) (bool, bool)
- func (b ResponseBlock) GetFloat(name string) (float64, bool)
- func (b ResponseBlock) GetInt(name string) (int64, bool)
- func (b ResponseBlock) GetList(name string) ([]string, bool)
- func (b ResponseBlock) GetString(name string) (string, bool)
- func (b ResponseBlock) Has(name string) bool
- func (b ResponseBlock) License() (License, bool)
- func (b ResponseBlock) Pos() token.Position
- func (b ResponseBlock) PreambleDescription() string
- func (b ResponseBlock) PreambleLines() []string
- func (b ResponseBlock) PreambleTitle() string
- func (b ResponseBlock) Properties() iter.Seq[Property]
- func (b ResponseBlock) Prose() string
- func (b ResponseBlock) ProseLines() []string
- func (b ResponseBlock) SecurityRequirements() []security.Requirement
- func (b ResponseBlock) Title() string
- func (b ResponseBlock) Walk(w Walker)
- func (b ResponseBlock) YAMLBlocks() iter.Seq[RawYAML]
- type RouteBlock
- func (b RouteBlock) AnnotationArg() (string, bool)
- func (b RouteBlock) AnnotationKind() AnnotationKind
- func (b RouteBlock) Contact() (Contact, error)
- func (b RouteBlock) Description() string
- func (b RouteBlock) Diagnostics() []Diagnostic
- func (b RouteBlock) Extensions() iter.Seq[Extension]
- func (b RouteBlock) GetBool(name string) (bool, bool)
- func (b RouteBlock) GetFloat(name string) (float64, bool)
- func (b RouteBlock) GetInt(name string) (int64, bool)
- func (b RouteBlock) GetList(name string) ([]string, bool)
- func (b RouteBlock) GetString(name string) (string, bool)
- func (b RouteBlock) Has(name string) bool
- func (b RouteBlock) License() (License, bool)
- func (b RouteBlock) Pos() token.Position
- func (b RouteBlock) PreambleDescription() string
- func (b RouteBlock) PreambleLines() []string
- func (b RouteBlock) PreambleTitle() string
- func (b RouteBlock) Properties() iter.Seq[Property]
- func (b RouteBlock) Prose() string
- func (b RouteBlock) ProseLines() []string
- func (b RouteBlock) SecurityRequirements() []security.Requirement
- func (b RouteBlock) Title() string
- func (b RouteBlock) Walk(w Walker)
- func (b RouteBlock) YAMLBlocks() iter.Seq[RawYAML]
- type Severity
- type Token
- type TokenKind
- type TypedValue
- type UnboundBlock
- func (b UnboundBlock) AnnotationArg() (string, bool)
- func (b UnboundBlock) AnnotationKind() AnnotationKind
- func (b UnboundBlock) Contact() (Contact, error)
- func (b UnboundBlock) Description() string
- func (b UnboundBlock) Diagnostics() []Diagnostic
- func (b UnboundBlock) Extensions() iter.Seq[Extension]
- func (b UnboundBlock) GetBool(name string) (bool, bool)
- func (b UnboundBlock) GetFloat(name string) (float64, bool)
- func (b UnboundBlock) GetInt(name string) (int64, bool)
- func (b UnboundBlock) GetList(name string) ([]string, bool)
- func (b UnboundBlock) GetString(name string) (string, bool)
- func (b UnboundBlock) Has(name string) bool
- func (b UnboundBlock) License() (License, bool)
- func (b UnboundBlock) Pos() token.Position
- func (b UnboundBlock) PreambleDescription() string
- func (b UnboundBlock) PreambleLines() []string
- func (b UnboundBlock) PreambleTitle() string
- func (b UnboundBlock) Properties() iter.Seq[Property]
- func (b UnboundBlock) Prose() string
- func (b UnboundBlock) ProseLines() []string
- func (b UnboundBlock) SecurityRequirements() []security.Requirement
- func (b UnboundBlock) Title() string
- func (b UnboundBlock) Walk(w Walker)
- func (b UnboundBlock) YAMLBlocks() iter.Seq[RawYAML]
- type ValueShape
- type Walker
Constants ¶
const ( KwMaximum = "maximum" KwMinimum = "minimum" KwMultipleOf = "multipleOf" KwMaxLength = "maxLength" KwMinLength = "minLength" KwPattern = "pattern" KwMaxItems = "maxItems" KwMinItems = "minItems" KwUnique = "unique" KwCollectionFormat = "collectionFormat" KwDefault = "default" KwExample = "example" KwEnum = "enum" KwRequired = "required" KwReadOnly = "readOnly" KwDiscriminator = "discriminator" KwDeprecated = "deprecated" KwIn = "in" KwSchemes = "schemes" KwVersion = "version" KwHost = "host" KwBasePath = "basePath" KwLicense = "license" KwContact = "contact" KwConsumes = "consumes" KwProduces = "produces" KwSecurity = "security" KwSecurityDefinitions = "securityDefinitions" KwResponses = "responses" KwParameters = "parameters" KwExtensions = "extensions" KwInfoExtensions = "infoExtensions" KwTOS = "tos" KwExternalDocs = "externalDocs" )
Canonical keyword names. These constants are the single source of truth for spelling: every Property's Keyword.Name compares equal to exactly one of them. Consumers that switch on Keyword.Name should reference these constants rather than re-declaring the strings — schema/walker.go and the bridge dispatchers in routes/parameters/ responses/operations/items/spec all dispatch on these names.
Sections (numeric validations / length validations / schema decorators / boolean markers / param-location / meta single-line / raw-block) follow the same order as the keywords table below.
const AllDepths = -1
AllDepths is the FilterDepth sentinel meaning "fire property callbacks regardless of ItemsDepth". Use it explicitly rather than -1 so the intent reads at the call site.
const AnnotationPrefix = "swagger:"
AnnotationPrefix is the literal that introduces every codescan annotation header. Centralised so callers and tests reference the single source of truth rather than the bare literal.
Variables ¶
This section is empty.
Functions ¶
func FormatToken ¶
FormatToken renders a token compactly for diagnostics and tests. Avoids leaking internal kinds in production output.
func NormalizeIn ¶
NormalizeIn returns the canonical OAS v2 parameter-location value matching raw, case-insensitively, against the closed vocabulary declared on KwIn (`query` / `path` / `header` / `body` / `formData`). Returns ("", false) when raw is not recognised.
When allowFormAlias is true, the routes-inline-param affordance from v1 is enabled: a raw value of `form` (case-insensitive) is accepted and normalised to `formData`. This is documented in observed-quirks Q27 and is intentionally contained to internal/parsers/routebody — every other capture site MUST pass allowFormAlias=false so the canonical OAS v2 vocabulary is the single source of truth.
The normalisation here mirrors what the grammar's enum-option parser does for typed KwIn properties (parser.go:740, strings.EqualFold). It exists as a public helper because three capture sites read `in:` by scanning doc text directly rather than going through grammar's typed property path:
- internal/builders/parameters/doc_signals.go (scanInLocation)
- internal/builders/responses/doc_signals.go (scanInLocation)
- internal/parsers/routebody/parameters.go (applyParamLine)
All three route through this helper so case-insensitivity is enforced uniformly and the closed vocabulary lives in one place.
Q29 (2026-06-03) — go-swagger-generated code emits capitalised forms like `in: Body`; the pre-fix strict-case map lookup silently miscategorised them, dropping fields to the `query` default.
Types ¶
type AnnotationKind ¶
type AnnotationKind int
AnnotationKind identifies the top-level swagger:<name> directive.
const ( AnnUnknown AnnotationKind = iota AnnModel // swagger:model AnnResponse // swagger:response AnnParameters // swagger:parameters AnnRoute // swagger:route AnnOperation // swagger:operation AnnMeta // swagger:meta AnnStrfmt // swagger:strfmt AnnAlias // swagger:alias AnnName // swagger:name AnnAllOf // swagger:allOf AnnEnum // swagger:enum AnnIgnore // swagger:ignore AnnDefaultName // swagger:default — value-only classifier annotation AnnType // swagger:type AnnFile // swagger:file )
func AnnotationKindFromName ¶
func AnnotationKindFromName(name string) AnnotationKind
AnnotationKindFromName resolves the swagger:<name> label to its kind. Returns AnnUnknown for labels outside the recognised set.
func (AnnotationKind) String ¶
func (a AnnotationKind) String() string
String renders an AnnotationKind as its source label.
type Block ¶
type Block interface {
Pos() token.Position
Title() string
Description() string
Diagnostics() []Diagnostic
AnnotationKind() AnnotationKind
Properties() iter.Seq[Property]
YAMLBlocks() iter.Seq[RawYAML]
Extensions() iter.Seq[Extension]
SecurityRequirements() []security.Requirement
Contact() (Contact, error)
License() (License, bool)
// Walk dispatches properties / prose / extensions / diagnostics
// through the callbacks set on w. See walker.go for the contract.
Walk(w Walker)
// ProseLines returns the cleaned prose lines (TITLE + DESC) in
// source order, with blank lines preserved as empty strings.
ProseLines() []string
// PreambleLines returns prose lines that appear BEFORE the block's
// annotation. For UnboundBlock (no annotation), returns the same as
// ProseLines. Schema and meta builders consume only pre-annotation
// prose for title/description; routes/operations consult ProseLines()
// and observe post-annotation text too.
PreambleLines() []string
// PreambleTitle / PreambleDescription return the
// title/description computed from PreambleLines (pre-annotation
// prose only). Schema's top-level model builder uses these so
// post-annotation prose reads as body content rather than
// title/description.
PreambleTitle() string
PreambleDescription() string
// Prose returns the entire prose surface (TITLE + DESC tokens
// in source order) joined with "\n", with internal blanks
// preserved as paragraph breaks and a single trailing blank
// dropped.
//
// Used by field-level callers (struct field / interface method
// docs) where the entire prose is the description and there's
// no separate title concept.
Prose() string
Has(name string) bool
GetFloat(name string) (float64, bool)
GetInt(name string) (int64, bool)
GetBool(name string) (bool, bool)
GetString(name string) (string, bool)
GetList(name string) ([]string, bool)
// AnnotationArg returns the first positional identifier argument
// of the block's primary annotation (e.g. "Pet" for
// `swagger:model Pet`, "date-time" for `swagger:strfmt
// date-time`, the IDENT_NAME for `swagger:name fooBar`).
// Returns ("", false) when the annotation has no arg or carries
// only an empty/whitespace one. Bare annotations (e.g.
// `swagger:model` without a name) return ("", false); callers
// distinguish "annotation present" via AnnotationKind().
//
// Convergence accessor — replaces type-asserting on each typed
// Block kind to read its Name / Args[0] field. Used by Walker
// callbacks that don't care which classifier flavour they're
// looking at, only what its IDENT_NAME-style argument is.
// See README §block-shapes.
AnnotationArg() (string, bool)
}
Block is the interface every typed AST node implements. One Block corresponds to one Go comment group's parsed content.
The typed Block hierarchy matches the family productions:
- SchemaBlock variants: ModelBlock, ResponseBlock, ParametersBlock, NameBlock
- OperationFamilyBlock: RouteBlock, InlineOperationBlock
- MetaBlock
- ClassifierBlock variants for the classifier annotations
- UnboundBlock for the no-annotation case
Details ¶
See README §parser-contract and §block-shapes for the per-Block contracts.
func NewSyntheticBlock ¶
NewSyntheticBlock builds a Block from a manually-curated set of properties. Used by sub-parsers (routebody, future input modes) that lower a non-grammar text surface into the standard Block shape so consumers can dispatch through the usual Walker.
title and description become the Block's Title()/Description(), also surfaced via Prose() with internal blank separation. pos is the source position of the synthetic block's head — Properties that lack their own Pos inherit it implicitly when consumers build diagnostics.
The returned Block exposes empty Diagnostics(), AnnotationKind() == AnnUnknown, no YAML blocks, no extensions, and no security requirements. AnnotationArg() returns ("", false). Walk fires Title/Description first when non-empty, then properties in slice order — the regular Walker contract. See README §synthetic-block.
func Parse ¶
func Parse(cg *ast.CommentGroup, fset *token.FileSet) Block
Parse is the convenience wrapper around NewParser(fset).Parse(cg).
func ParseAll ¶
func ParseAll(cg *ast.CommentGroup, fset *token.FileSet) []Block
ParseAll is the convenience wrapper around NewParser(fset).ParseAll(cg).
func ParseTokens ¶
ParseTokens runs the parser on a pre-lexed token stream. Useful for tests and LSP scenarios.
type ClassifierBlock ¶
type ClassifierBlock struct {
Args []Token
// contains filtered or unexported fields
}
ClassifierBlock covers single-line classifier annotations: strfmt / allOf / ignore / alias / file / type / default. The Args slice carries the lexer-tokenised positional arguments.
func (*ClassifierBlock) AnnotationArg ¶
func (b *ClassifierBlock) AnnotationArg() (string, bool)
AnnotationArg returns the first positional argument's text when non-empty (single-word capture). Bare classifier annotations (e.g. `swagger:ignore`, `swagger:alias`) return ("", false).
func (ClassifierBlock) AnnotationKind ¶
func (b ClassifierBlock) AnnotationKind() AnnotationKind
func (ClassifierBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (ClassifierBlock) Description ¶
func (b ClassifierBlock) Description() string
func (ClassifierBlock) Diagnostics ¶
func (b ClassifierBlock) Diagnostics() []Diagnostic
func (ClassifierBlock) Extensions ¶
func (ClassifierBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (ClassifierBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (ClassifierBlock) PreambleDescription ¶
func (b ClassifierBlock) PreambleDescription() string
func (ClassifierBlock) PreambleLines ¶
func (b ClassifierBlock) PreambleLines() []string
func (ClassifierBlock) PreambleTitle ¶
func (b ClassifierBlock) PreambleTitle() string
func (ClassifierBlock) Properties ¶
func (ClassifierBlock) Prose ¶
func (b ClassifierBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (ClassifierBlock) ProseLines ¶
func (b ClassifierBlock) ProseLines() []string
func (ClassifierBlock) SecurityRequirements ¶
func (b ClassifierBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (ClassifierBlock) Walk ¶
func (b ClassifierBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (ClassifierBlock) YAMLBlocks ¶
type Code ¶
type Code string
Code is a stable identifier for a class of Diagnostic.
const ( CodeInvalidNumber Code = "parse.invalid-number" CodeInvalidInteger Code = "parse.invalid-integer" CodeInvalidBoolean Code = "parse.invalid-boolean" CodeInvalidEnumOption Code = "parse.invalid-enum-option" CodeContextInvalid Code = "parse.context-invalid" CodeInvalidExtension Code = "parse.invalid-extension-name" // CodeInvalidYAMLExtensions fires when the body of an // `extensions:` raw block fails YAML parsing. The block is // skipped (no Extension entries emitted) and a warning is raised. CodeInvalidYAMLExtensions Code = "parse.invalid-yaml-extensions" CodeUnterminatedYAML Code = "parse.unterminated-yaml" CodeInvalidAnnotation Code = "parse.invalid-annotation" CodeInvalidTypeRef Code = "parse.invalid-type-ref" CodeUnexpectedToken Code = "parse.unexpected-token" CodeMalformedOperation Code = "parse.malformed-operation" CodeMissingRequiredArg Code = "parse.missing-required-arg" // CodeShapeMismatch fires when a keyword is applied to a schema // whose resolved Swagger type doesn't match the keyword's domain // (e.g. `pattern: ^a$` on an integer field). Emitted by // internal/builders/validations.IsLegalForType callers. CodeShapeMismatch Code = "validate.shape-mismatch" // CodeAmbiguousEmbed fires when two embedded types of a parent // struct (or struct embed-chains at the same depth) both promote // a property with the same JSON name but different Go names. Go's // own rule is to not promote such ambiguous fields; codescan // currently emits a last-write-wins schema regardless. The // diagnostic surfaces the case so authors can disambiguate. CodeAmbiguousEmbed Code = "validate.ambiguous-embed" // CodeUnsupportedInSimpleSchema fires when the schema builder // running in SimpleSchema mode produces an outcome that OAS v2 // does not allow on a parameter/header (object type, $ref, allOf, // properties, …). The diagnostic is emitted at exit and the // target is reset to empty `{}` — honest over lossy. Reaching // this code path typically means a non-body parameter or response // header was typed as a struct or interface that the recognizer // cascade couldn't reduce to a primitive. CodeUnsupportedInSimpleSchema Code = "validate.unsupported-in-simple-schema" )
Diagnostic codes. The `parse.*` prefix marks lexer/parser-level observations; `validate.*` marks semantic-validation observations emitted by the builder layer (typically through the internal/builders/validations package).
type Contact ¶
type Contact struct {
Name, Email, URL string
}
Contact is the typed shape of a `contact:` inline value on a swagger:meta block. The convention is:
contact: <Name> <email> <URL>
where each part is optional in the order written: the parser recognises a `Name <email>` head (Go's net/mail.ParseAddress form) followed by an optional URL. A bare email without a name is also accepted. Empty or unrecognised inputs return (Contact{}, false) from Block.Contact().
type DefaultParser ¶
type DefaultParser struct {
// contains filtered or unexported fields
}
DefaultParser is the concrete Parser implementation.
func NewParser ¶
func NewParser(fset *token.FileSet, opts ...Option) *DefaultParser
NewParser constructs a DefaultParser bound to a FileSet (needed to map *ast.CommentGroup positions to absolute source positions).
func (*DefaultParser) Parse ¶
func (p *DefaultParser) Parse(cg *ast.CommentGroup) Block
func (*DefaultParser) ParseAll ¶
func (p *DefaultParser) ParseAll(cg *ast.CommentGroup) []Block
ParseAll returns one Block per annotation in cg, in source order. A comment group with no annotation yields a single-element slice holding an UnboundBlock; a single-annotation comment yields the same Block as Parse, wrapped in a slice; multi-annotation comments yield one Block per annotation.
Token partition: each annotation owns the slice of tokens from its index up to (but excluding) the next annotation. The first annotation also owns the pre-annotation prose, so its PreambleTitle / PreambleDescription match Parse(cg)'s. Body tokens between annotations attach to the *preceding* annotation.
Multi-annotation comments like
// swagger:model // swagger:strfmt date-time
pair a schema-family annotation with a classifier; the schema builder's Walker dispatches on each Block's AnnotationKind() without further partitioning.
func (*DefaultParser) ParseAs ¶
func (p *DefaultParser) ParseAs(kind AnnotationKind, text string, pos token.Position) Block
type Diagnostic ¶
Diagnostic is one observation about a comment block.
func (Diagnostic) String ¶
func (d Diagnostic) String() string
String renders a Diagnostic in compiler-style one-line form.
type EnumDeclBlock ¶
type EnumDeclBlock struct {
Name string // "" when absent
InlineForm enumArgsForm
InlineArgs []Token // values fragment as a typed token, when inline values were given
BodyValues string // populated when a multi-line RAW_VALUE_ENUM body was present
// contains filtered or unexported fields
}
EnumDeclBlock is produced by `swagger:enum [name] [values…]`. The optional multi-line value-list is carried in BodyValues when present (lexer accumulates the body as RAW_VALUE_ENUM).
func (*EnumDeclBlock) AnnotationArg ¶
func (b *EnumDeclBlock) AnnotationArg() (string, bool)
AnnotationArg returns the IDENT_NAME arg (`status` for `swagger:enum status`) or ("", false) when the enum was declared inline-only (`swagger:enum red green blue`) or as a pure body block.
func (EnumDeclBlock) AnnotationKind ¶
func (b EnumDeclBlock) AnnotationKind() AnnotationKind
func (EnumDeclBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (EnumDeclBlock) Description ¶
func (b EnumDeclBlock) Description() string
func (EnumDeclBlock) Diagnostics ¶
func (b EnumDeclBlock) Diagnostics() []Diagnostic
func (EnumDeclBlock) Extensions ¶
func (EnumDeclBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (EnumDeclBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (EnumDeclBlock) PreambleDescription ¶
func (b EnumDeclBlock) PreambleDescription() string
func (EnumDeclBlock) PreambleLines ¶
func (b EnumDeclBlock) PreambleLines() []string
func (EnumDeclBlock) PreambleTitle ¶
func (b EnumDeclBlock) PreambleTitle() string
func (EnumDeclBlock) Properties ¶
func (EnumDeclBlock) Prose ¶
func (b EnumDeclBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (EnumDeclBlock) ProseLines ¶
func (b EnumDeclBlock) ProseLines() []string
func (EnumDeclBlock) SecurityRequirements ¶
func (b EnumDeclBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (EnumDeclBlock) Walk ¶
func (b EnumDeclBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (EnumDeclBlock) YAMLBlocks ¶
type Extension ¶
Extension is one x-* vendor entry under an extensions: block.
Value carries the YAML-typed nested value (`bool` / `float64` / `string` / `[]any` / `map[string]any`). The parser pipes the body through `internal/parsers/yaml.TypedExtensions`, so consumers can rely on JSON-normalised types — never `map[any]any`.
Source carries the keyword that produced the entry: KwExtensions for `extensions:` blocks (top-level vendor extensions) or KwInfoExtensions for `infoExtensions:` blocks (Info-scoped vendor extensions, meta-only). Consumers that need to route entries to different targets — meta's swspec.Extensions vs swspec.Info.Extensions — switch on this field; consumers that treat extensions uniformly (routes / operations) can ignore it.
type InlineOperationBlock ¶
type InlineOperationBlock struct {
Method string
Path string
Tags []string
OpID string
// contains filtered or unexported fields
}
InlineOperationBlock is produced by `swagger:operation METHOD /path [tags] opID`. Body may carry an OPAQUE_YAML in addition to inline keyword raw-blocks.
func (InlineOperationBlock) AnnotationArg ¶
AnnotationArg default — Block kinds whose annotation takes no identifier argument (UnboundBlock, MetaBlock, RouteBlock, InlineOperationBlock, ParametersBlock — the latter has multiple args but conceptually it's a list, not a single IDENT_NAME). Typed kinds with a single IDENT_NAME override this method.
func (InlineOperationBlock) AnnotationKind ¶
func (b InlineOperationBlock) AnnotationKind() AnnotationKind
func (InlineOperationBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (InlineOperationBlock) Description ¶
func (b InlineOperationBlock) Description() string
func (InlineOperationBlock) Diagnostics ¶
func (b InlineOperationBlock) Diagnostics() []Diagnostic
func (InlineOperationBlock) Extensions ¶
func (InlineOperationBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (InlineOperationBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (InlineOperationBlock) PreambleDescription ¶
func (b InlineOperationBlock) PreambleDescription() string
func (InlineOperationBlock) PreambleLines ¶
func (b InlineOperationBlock) PreambleLines() []string
func (InlineOperationBlock) PreambleTitle ¶
func (b InlineOperationBlock) PreambleTitle() string
func (InlineOperationBlock) Properties ¶
func (InlineOperationBlock) Prose ¶
func (b InlineOperationBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (InlineOperationBlock) ProseLines ¶
func (b InlineOperationBlock) ProseLines() []string
func (InlineOperationBlock) SecurityRequirements ¶
func (b InlineOperationBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (InlineOperationBlock) Walk ¶
func (b InlineOperationBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (InlineOperationBlock) YAMLBlocks ¶
type Keyword ¶
type Keyword struct {
Name string
Aliases []string
Shape ValueShape
Values []string // populated when Shape == ShapeEnumOption
// Contexts is the set of family contexts the keyword is legal in.
// Used by the parser layer for non-fatal context-invalid warnings.
Contexts []KeywordContext
}
Keyword describes one recognisable keyword: <value> form.
type KeywordContext ¶
type KeywordContext int
KeywordContext is a family-level context where a keyword is legal. Distinct from AnnotationKind because validations are legal across several annotation kinds (model + parameters + response, etc.).
const ( CtxParam KeywordContext = iota CtxHeader CtxSchema CtxItems CtxRoute CtxOperation CtxMeta CtxResponse )
func (KeywordContext) String ¶
func (c KeywordContext) String() string
String renders a KeywordContext for diagnostics.
type License ¶
type License struct {
Name, URL string
}
License is the typed shape of a `license:` inline value:
license: <Name> <URL>
where Name is everything before the URL prefix and URL is the scheme-anchored remainder. A line without a URL keeps Name and leaves URL empty. Empty input returns (License{}, false) from Block.License().
type Line ¶
Line is one preprocessed comment line ready for the lexer.
Text has the Go comment markers (// /* */) stripped along with the godoc continuation decoration (leading whitespace, asterisks, slashes, optional markdown table pipe). Used for keyword and annotation classification.
Raw is the same source line with only the comment marker removed — content whitespace, indentation, and list markers are preserved. Used by the body accumulator so YAML / nested-map indentation survives intact.
Pos points to the first character of Text in the source file.
func Preprocess ¶
func Preprocess(cg *ast.CommentGroup, fset *token.FileSet) []Line
Preprocess turns a Go comment group into a position-tagged []Line. Returns nil for nil inputs. Pure: no syscalls, no side-effects.
Line endings are normalised before line splitting (\r\n → \n, lone \r → \n). See README §preprocess-contract.
type MetaBlock ¶
type MetaBlock struct {
// contains filtered or unexported fields
}
MetaBlock is produced by `swagger:meta`.
func (MetaBlock) AnnotationArg ¶
AnnotationArg default — Block kinds whose annotation takes no identifier argument (UnboundBlock, MetaBlock, RouteBlock, InlineOperationBlock, ParametersBlock — the latter has multiple args but conceptually it's a list, not a single IDENT_NAME). Typed kinds with a single IDENT_NAME override this method.
func (MetaBlock) AnnotationKind ¶
func (b MetaBlock) AnnotationKind() AnnotationKind
func (MetaBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (MetaBlock) Description ¶
func (b MetaBlock) Description() string
func (MetaBlock) Diagnostics ¶
func (b MetaBlock) Diagnostics() []Diagnostic
func (MetaBlock) Extensions ¶
func (MetaBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (MetaBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (MetaBlock) PreambleDescription ¶
func (b MetaBlock) PreambleDescription() string
func (MetaBlock) PreambleLines ¶
func (b MetaBlock) PreambleLines() []string
func (MetaBlock) PreambleTitle ¶
func (b MetaBlock) PreambleTitle() string
func (MetaBlock) Properties ¶
func (MetaBlock) Prose ¶
func (b MetaBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (MetaBlock) ProseLines ¶
func (b MetaBlock) ProseLines() []string
func (MetaBlock) SecurityRequirements ¶
func (b MetaBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (MetaBlock) Walk ¶
func (b MetaBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (MetaBlock) YAMLBlocks ¶
type ModelBlock ¶
type ModelBlock struct {
Name string
// contains filtered or unexported fields
}
ModelBlock is produced by `swagger:model [Name]`.
func (*ModelBlock) AnnotationArg ¶
func (b *ModelBlock) AnnotationArg() (string, bool)
AnnotationArg returns the IDENT_NAME arg (`Pet` for `swagger:model Pet`) or ("", false) for a bare `swagger:model`.
func (ModelBlock) AnnotationKind ¶
func (b ModelBlock) AnnotationKind() AnnotationKind
func (ModelBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (ModelBlock) Description ¶
func (b ModelBlock) Description() string
func (ModelBlock) Diagnostics ¶
func (b ModelBlock) Diagnostics() []Diagnostic
func (ModelBlock) Extensions ¶
func (ModelBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (ModelBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (ModelBlock) PreambleDescription ¶
func (b ModelBlock) PreambleDescription() string
func (ModelBlock) PreambleLines ¶
func (b ModelBlock) PreambleLines() []string
func (ModelBlock) PreambleTitle ¶
func (b ModelBlock) PreambleTitle() string
func (ModelBlock) Properties ¶
func (ModelBlock) Prose ¶
func (b ModelBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (ModelBlock) ProseLines ¶
func (b ModelBlock) ProseLines() []string
func (ModelBlock) SecurityRequirements ¶
func (b ModelBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (ModelBlock) Walk ¶
func (b ModelBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (ModelBlock) YAMLBlocks ¶
type NameBlock ¶
type NameBlock struct {
Name string
// contains filtered or unexported fields
}
NameBlock is produced by `swagger:name <member-name>`. The annotation overrides a struct field's / interface method's JSON property name (or schema member name) without mutating the surrounding Go identifier. Name carries the IDENT_NAME argument.
func (*NameBlock) AnnotationArg ¶
AnnotationArg returns the IDENT_NAME arg. Bare `swagger:name` is rejected at parse time (CodeMissingRequiredArg); ("", false) only appears on the diagnostic path.
func (NameBlock) AnnotationKind ¶
func (b NameBlock) AnnotationKind() AnnotationKind
func (NameBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (NameBlock) Description ¶
func (b NameBlock) Description() string
func (NameBlock) Diagnostics ¶
func (b NameBlock) Diagnostics() []Diagnostic
func (NameBlock) Extensions ¶
func (NameBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (NameBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (NameBlock) PreambleDescription ¶
func (b NameBlock) PreambleDescription() string
func (NameBlock) PreambleLines ¶
func (b NameBlock) PreambleLines() []string
func (NameBlock) PreambleTitle ¶
func (b NameBlock) PreambleTitle() string
func (NameBlock) Properties ¶
func (NameBlock) Prose ¶
func (b NameBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (NameBlock) ProseLines ¶
func (b NameBlock) ProseLines() []string
func (NameBlock) SecurityRequirements ¶
func (b NameBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (NameBlock) Walk ¶
func (b NameBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (NameBlock) YAMLBlocks ¶
type Option ¶
type Option func(*DefaultParser)
Option configures a DefaultParser.
func WithDiagnosticSink ¶
func WithDiagnosticSink(sink func(Diagnostic)) Option
WithDiagnosticSink streams diagnostics to a callback in addition to accumulating them on the returned Block.
type ParametersBlock ¶
type ParametersBlock struct {
OperationIDs []string
// contains filtered or unexported fields
}
ParametersBlock is produced by `swagger:parameters T1 T2 …`.
func (ParametersBlock) AnnotationArg ¶
AnnotationArg default — Block kinds whose annotation takes no identifier argument (UnboundBlock, MetaBlock, RouteBlock, InlineOperationBlock, ParametersBlock — the latter has multiple args but conceptually it's a list, not a single IDENT_NAME). Typed kinds with a single IDENT_NAME override this method.
func (ParametersBlock) AnnotationKind ¶
func (b ParametersBlock) AnnotationKind() AnnotationKind
func (ParametersBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (ParametersBlock) Description ¶
func (b ParametersBlock) Description() string
func (ParametersBlock) Diagnostics ¶
func (b ParametersBlock) Diagnostics() []Diagnostic
func (ParametersBlock) Extensions ¶
func (ParametersBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (ParametersBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (ParametersBlock) PreambleDescription ¶
func (b ParametersBlock) PreambleDescription() string
func (ParametersBlock) PreambleLines ¶
func (b ParametersBlock) PreambleLines() []string
func (ParametersBlock) PreambleTitle ¶
func (b ParametersBlock) PreambleTitle() string
func (ParametersBlock) Properties ¶
func (ParametersBlock) Prose ¶
func (b ParametersBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (ParametersBlock) ProseLines ¶
func (b ParametersBlock) ProseLines() []string
func (ParametersBlock) SecurityRequirements ¶
func (b ParametersBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (ParametersBlock) Walk ¶
func (b ParametersBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (ParametersBlock) YAMLBlocks ¶
type Parser ¶
type Parser interface {
Parse(cg *ast.CommentGroup) Block
ParseAll(cg *ast.CommentGroup) []Block
ParseText(text string, pos token.Position) Block
ParseAs(kind AnnotationKind, text string, pos token.Position) Block
}
Parser is the consumer contract for the grammar parser. The package ships *DefaultParser; the interface exists so tests can substitute a mock that fabricates Block values without running the full lex pipeline.
Details ¶
See README §parser-contract for the family dispatch table and the body-token consumption rules.
type Property ¶
type Property struct {
Keyword Keyword
Pos token.Position
Value string
Body string
Raw string
Typed TypedValue
ItemsDepth int
}
Property is one keyword:value (or keyword body) attached to a Block.
For inline-value keywords (Number / Integer / Bool / String / EnumOption / CommaList shapes), Value is the raw string and Typed carries the lexically-typed form.
For body keywords (ShapeRawBlock / ShapeRawValue), Body holds the accumulated body content, Raw holds the verbatim source content, and Typed.Type indicates the body shape.
ItemsDepth records the leading items.* depth from the keyword head.
Details ¶
See README §property-shape for the field-population matrix and the AsList unification rule.
func (Property) AsList ¶
AsList returns the token list represented by p, unifying every list-shaped surface form the grammar accepts (inline comma list, multi-line indented, YAML `- ` markers, or any combination).
Details ¶
See README §property-shape (`AsList — unified list extraction`) for the surface forms, the algorithm, and the explicit non-targets (enum values, routebody Parameters chunks, raw YAML bodies).
func (Property) IsTyped ¶
IsTyped reports whether the property carries a primitive-typed value the caller can consume directly without further coercion.
True when Typed.Type is one of the primitive shapes — Number, Integer, Bool, EnumOption — meaning the matching Typed.* field is populated and authoritative. False otherwise:
- ShapeNone — typing was not applied (ShapeString keywords like `pattern` keep the raw value in Property.Value), or typing failed and a diagnostic was emitted.
- ShapeRawBlock / ShapeRawValue / ShapeCommaList / ShapeString — the value's interpretation depends on the resolved spec type (e.g. `default: 1.5` against a float-typed schema), so the consumer must coerce against schemaType+schemaFormat.
Canonical use site:
if p.IsTyped() {
// read p.Typed.<field> matching p.Keyword.Shape
} else {
// coerce p.Value against the resolved schema type
}
Replaces the explicit `switch p.Typed.Type` boilerplate consumers would otherwise need at every call site.
type RawYAML ¶
RawYAML is one captured `--- … ---` body. The parser does not parse the YAML — it isolates the body so the analyzer can hand it to internal/parsers/yaml/.
type ResponseBlock ¶
type ResponseBlock struct {
Name string
// contains filtered or unexported fields
}
ResponseBlock is produced by `swagger:response [Name]`.
func (*ResponseBlock) AnnotationArg ¶
func (b *ResponseBlock) AnnotationArg() (string, bool)
AnnotationArg returns the IDENT_NAME arg or ("", false) for a bare `swagger:response`.
func (ResponseBlock) AnnotationKind ¶
func (b ResponseBlock) AnnotationKind() AnnotationKind
func (ResponseBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (ResponseBlock) Description ¶
func (b ResponseBlock) Description() string
func (ResponseBlock) Diagnostics ¶
func (b ResponseBlock) Diagnostics() []Diagnostic
func (ResponseBlock) Extensions ¶
func (ResponseBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (ResponseBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (ResponseBlock) PreambleDescription ¶
func (b ResponseBlock) PreambleDescription() string
func (ResponseBlock) PreambleLines ¶
func (b ResponseBlock) PreambleLines() []string
func (ResponseBlock) PreambleTitle ¶
func (b ResponseBlock) PreambleTitle() string
func (ResponseBlock) Properties ¶
func (ResponseBlock) Prose ¶
func (b ResponseBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (ResponseBlock) ProseLines ¶
func (b ResponseBlock) ProseLines() []string
func (ResponseBlock) SecurityRequirements ¶
func (b ResponseBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (ResponseBlock) Walk ¶
func (b ResponseBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (ResponseBlock) YAMLBlocks ¶
type RouteBlock ¶
type RouteBlock struct {
Method string
Path string
Tags []string
OpID string
// contains filtered or unexported fields
}
RouteBlock is produced by `swagger:route METHOD /path [tags] opID`. swagger:route's body is inline keyword raw-blocks and **never** an OPAQUE_YAML.
func (RouteBlock) AnnotationArg ¶
AnnotationArg default — Block kinds whose annotation takes no identifier argument (UnboundBlock, MetaBlock, RouteBlock, InlineOperationBlock, ParametersBlock — the latter has multiple args but conceptually it's a list, not a single IDENT_NAME). Typed kinds with a single IDENT_NAME override this method.
func (RouteBlock) AnnotationKind ¶
func (b RouteBlock) AnnotationKind() AnnotationKind
func (RouteBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (RouteBlock) Description ¶
func (b RouteBlock) Description() string
func (RouteBlock) Diagnostics ¶
func (b RouteBlock) Diagnostics() []Diagnostic
func (RouteBlock) Extensions ¶
func (RouteBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (RouteBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (RouteBlock) PreambleDescription ¶
func (b RouteBlock) PreambleDescription() string
func (RouteBlock) PreambleLines ¶
func (b RouteBlock) PreambleLines() []string
func (RouteBlock) PreambleTitle ¶
func (b RouteBlock) PreambleTitle() string
func (RouteBlock) Properties ¶
func (RouteBlock) Prose ¶
func (b RouteBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (RouteBlock) ProseLines ¶
func (b RouteBlock) ProseLines() []string
func (RouteBlock) SecurityRequirements ¶
func (b RouteBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (RouteBlock) Walk ¶
func (b RouteBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (RouteBlock) YAMLBlocks ¶
type Severity ¶
type Severity int
Severity classifies a Diagnostic's seriousness. The parser never aborts; callers (analyzers, LSP, the CLI) decide policy by severity. See README §diagnostics.
type Token ¶
type Token struct {
Kind TokenKind
Pos token.Position
Name string // for TokenAnnotation / TokenKeyword: canonical label
SourceName string // keyword: literal as written (alias / case preserved)
Text string // payload for value tokens, prose lines, idents
Args []Token // for TokenAnnotation: positional argument tokens
ItemsDepth int // leading "items." depth (keyword tokens only)
Keyword string // for body tokens: parent keyword name
Body string // for body tokens: body content joined by "\n"
Raw string // verbatim source content (indentation preserved)
Truncated bool // body lexed without a closer (e.g. unmatched ---)
}
Token is one lexer-emitted item. Field population varies by kind:
- TokenAnnotation: Name = annotation label, Args are pre-tokenised argument tokens already disambiguated by the lexer (IDENT_NAME, JSON_VALUE, RAW_VALUE, TYPE_REF, HTTP_METHOD, URL_PATH, etc. — see README §annotation-args).
- TokenKeyword: Name = canonical keyword label; SourceName = the literal as it appeared (case / alias preserved); ItemsDepth = number of leading "items." segments stripped.
- TokenRawBlockBody / TokenRawValueBody: Keyword = the parent keyword; Body = body content joined by "\n"; Raw = verbatim source-indented content; ItemsDepth carried from the head if applicable.
- TokenOpaqueYaml: Body = body content (between fences).
- TokenIdentName / value-typed tokens: Text = payload string.
- TokenTitle / TokenDesc: Text = prose line content.
Pos is the source position of the first meaningful payload character.
func Lex ¶
Lex turns a preprocessed []Line into the token stream consumed by the grammar parser. Pipeline:
- Line classifier (lexLine): per-line classification into raw Tokens (annotation / keyword / fence / blank / text).
- Body accumulator: folds multi-line bodies (OPAQUE_YAML, RAW_BLOCK, RAW_VALUE) into single body tokens.
- Prose classifier: re-types surviving text tokens as TITLE / DESC.
The output stream ends in a single TokenEOF.
Details ¶
See README §lexer-contract for the per-stage rules, §raw-block-terminators for body-termination rules, and §prose-classification for the TITLE / DESC split heuristics.
type TokenKind ¶
type TokenKind int
TokenKind classifies a lexer-emitted token. The kinds map onto the grammar's terminal vocabulary:
- ANN_* → TokenAnnotation, Name carries the annotation label
- KW_* → TokenKeyword, Name carries the keyword label
- IDENT_NAME, JSON_VALUE, RAW_VALUE, TYPE_REF, HTTP_METHOD, URL_PATH → distinct kinds, payload in Text
- NUMBER_VALUE / INT_VALUE / BOOL_VALUE / STRING_VALUE / COMMA_LIST_VALUE / ENUM_OPTION_VALUE → distinct kinds
- RAW_BLOCK_<KW> → TokenRawBlockBody with Keyword = "consumes"/"produces"/…
- RAW_VALUE_<KW> → TokenRawValueBody with Keyword = "default"/"example"/"enum"
- OPAQUE_YAML → TokenOpaqueYaml
- TITLE / DESC / BLANK / EOF → TokenTitle / TokenDesc / TokenBlank / TokenEOF
The lexer also emits a few internal kinds (tokenYAMLFence, tokenText, tokenKeywordPre, tokenRawLine, tokenDirective) that are consumed by intermediate stages and never appear in the final stream the parser consumes.
const ( TokenEOF TokenKind = iota TokenBlank TokenTitle TokenDesc TokenAnnotation // ANN_* — Name = annotation label TokenKeyword // KW_* — Name = keyword label TokenIdentName // IDENT_NAME TokenJSONValue // JSON_VALUE TokenRawValue // RAW_VALUE TokenTypeRef // TYPE_REF TokenHTTPMethod // HTTP_METHOD TokenURLPath // URL_PATH TokenNumberValue // NUMBER_VALUE TokenIntValue // INT_VALUE TokenBoolValue // BOOL_VALUE TokenStringValue // STRING_VALUE TokenCommaListValue // COMMA_LIST_VALUE TokenEnumOption // ENUM_OPTION_VALUE TokenRawBlockBody // RAW_BLOCK_<KW> — Name = parent keyword TokenRawValueBody // RAW_VALUE_<KW> — Name = parent keyword TokenOpaqueYaml // OPAQUE_YAML )
type TypedValue ¶
type TypedValue struct {
Type ValueShape
Op string
Number float64
Integer int64
Boolean bool
String string
}
TypedValue carries the lexer-recognised value shape.
Op is the leading comparison operator stripped from a NumberValue ("<", "<=", ">", ">=", "="). Empty for non-Number values or when no operator was present. Accepts e.g. `maximum: <5`; the analyzer interprets Op + Number to decide inclusive vs exclusive semantics.
type UnboundBlock ¶
type UnboundBlock struct {
// contains filtered or unexported fields
}
UnboundBlock represents a comment group with no annotation line — e.g. a struct field's docstring.
func (UnboundBlock) AnnotationArg ¶
AnnotationArg default — Block kinds whose annotation takes no identifier argument (UnboundBlock, MetaBlock, RouteBlock, InlineOperationBlock, ParametersBlock — the latter has multiple args but conceptually it's a list, not a single IDENT_NAME). Typed kinds with a single IDENT_NAME override this method.
func (UnboundBlock) AnnotationKind ¶
func (b UnboundBlock) AnnotationKind() AnnotationKind
func (UnboundBlock) Contact ¶
Contact returns the typed Contact value parsed from the block's `contact:` inline keyword. Returns (Contact{}, nil) when no `contact:` appeared, or when its value is empty. A non-nil error signals a malformed `Name <email>` head — the caller decides whether to fail or warn. Parses on call.
func (UnboundBlock) Description ¶
func (b UnboundBlock) Description() string
func (UnboundBlock) Diagnostics ¶
func (b UnboundBlock) Diagnostics() []Diagnostic
func (UnboundBlock) Extensions ¶
func (UnboundBlock) GetList ¶
GetList returns the token list represented by the named keyword, unifying every list-shaped surface form the grammar accepts. Delegates to Property.AsList; see that method for the algorithm and accepted surface forms.
Returns (nil, false) when the keyword is absent. Returns (nil, true) when the keyword is present but every line trims to empty — the bool reports presence, not non-emptiness.
func (UnboundBlock) License ¶
License returns the typed License value parsed from the block's `license:` inline keyword, or (License{}, false) when no `license:` keyword appeared. Parses on call.
func (UnboundBlock) PreambleDescription ¶
func (b UnboundBlock) PreambleDescription() string
func (UnboundBlock) PreambleLines ¶
func (b UnboundBlock) PreambleLines() []string
func (UnboundBlock) PreambleTitle ¶
func (b UnboundBlock) PreambleTitle() string
func (UnboundBlock) Properties ¶
func (UnboundBlock) Prose ¶
func (b UnboundBlock) Prose() string
Prose joins the cached proseLines (TITLE + DESC + internal blanks, in source order) with "\n" and drops a single whitespace-only trailing line. The trim and join happen on the cached slice; no extra parse work.
func (UnboundBlock) ProseLines ¶
func (b UnboundBlock) ProseLines() []string
func (UnboundBlock) SecurityRequirements ¶
func (b UnboundBlock) SecurityRequirements() []security.Requirement
SecurityRequirements returns the typed list of `Security:` requirements parsed at lex time from the block's `security:` raw body, or nil when no `security:` keyword appeared. Each entry is a single-key map from scheme name → scope list, mirroring the shape OAS v2 expects on `spec.Operation.Security`.
func (UnboundBlock) Walk ¶
func (b UnboundBlock) Walk(w Walker)
Walk dispatches one Block through w. Nil callbacks are silently ignored. See Walker for the dispatch contract.
Walk reads only from b — it never mutates the Block or its properties. Walk is safe to call concurrently on the same Block from multiple goroutines as long as the Walker callbacks are themselves safe.
func (UnboundBlock) YAMLBlocks ¶
type ValueShape ¶
type ValueShape int
ValueShape names the lexical shape of a keyword's value, mapping directly onto the value terminals:
- ShapeNumber → NUMBER_VALUE
- ShapeInt → INT_VALUE
- ShapeBool → BOOL_VALUE
- ShapeString → STRING_VALUE
- ShapeCommaList → COMMA_LIST_VALUE
- ShapeEnumOption → ENUM_OPTION_VALUE (Values lists the closed set)
- ShapeRawBlock → RAW_BLOCK_<KW> (multi-line body terminal)
- ShapeRawValue → RAW_VALUE_<KW> (multi-line OR single-line body terminal)
See README §keyword-table for the per-shape callback dispatched by Walker.
const ( ShapeNone ValueShape = iota ShapeNumber ShapeInt ShapeBool ShapeString ShapeCommaList ShapeEnumOption ShapeRawBlock ShapeRawValue )
func (ValueShape) IsBody ¶
func (v ValueShape) IsBody() bool
IsBody reports whether the keyword's value is a multi-line body terminal (RAW_BLOCK_* or RAW_VALUE_*). Body keywords trigger the lexer's body accumulator.
func (ValueShape) String ¶
func (v ValueShape) String() string
String renders a ValueShape for diagnostics.
type Walker ¶
type Walker struct {
Title func(s string)
Description func(s string)
Number func(p Property, val float64, exclusive bool)
Integer func(p Property, val int64)
Bool func(p Property, val bool)
String func(p Property, val string)
Raw func(p Property)
Unknown func(p Property)
Extension func(ext Extension)
Diagnostic func(d Diagnostic)
FilterDepth int
}
Walker is the functional-visitor surface a Block exposes for bulk dispatch. Consumers wire only the callbacks they care about — every nil field is a silent no-op.
Details ¶
See README §walker-contract for the dispatch order, the per- Keyword.Shape callback table, the Number/Integer/Bool typing- failure rule, the FilterDepth gating, and the concurrency contract.