parser

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContainsUnescapedBrace

func ContainsUnescapedBrace(content string) bool

ContainsUnescapedBrace checks if string has unescaped { or }.

func ConvertToMultiLine

func ConvertToMultiLine(inlineLine, annotationName string) []string

ConvertToMultiLine converts inline format to multi-line for uniform processing This is a helper for debugging/testing

func CountUnescapedBraces

func CountUnescapedBraces(content string) (depth int, balanced bool)

CountUnescapedBraces counts brace depth ignoring escaped braces. Returns the final depth and whether braces are balanced.

func ExpandContentType

func ExpandContentType(shortName string) string

ExpandContentType expands short content-type names to full MIME types

func ExtractMetadata

func ExtractMetadata(line, annotationName string) string

ExtractMetadata extracts metadata from the opening line of an annotation Example: "@endpoint GET /users/{id} {" -> "GET /users/{id}" Example: "@server https://api.com {" -> "https://api.com" Uses position-based detection to preserve path parameters like {id}.

func IsInlineFormat

func IsInlineFormat(lines []string) bool

IsInlineFormat checks if an annotation uses inline format Inline format: @field { @description Test @format email } Multi-line format: @field {\n @description Test\n @format email\n}

func ParseBracedBlock

func ParseBracedBlock(lines []string) ([]string, error)

ParseBracedBlock extracts content within braces { } Returns the content lines and any error. Uses position-based detection: block delimiter is " {" (space + brace). This allows path parameters like {id} to coexist with block delimiters.

func ProtectEscapedAt

func ProtectEscapedAt(content string) string

ProtectEscapedAt replaces \@ with placeholder before splitting by @.

func RestoreEscapedAt

func RestoreEscapedAt(content string) string

RestoreEscapedAt restores placeholder back to \@.

func StartsWithUnescapedAt

func StartsWithUnescapedAt(line string) bool

StartsWithUnescapedAt checks if a line starts with an unescaped @ symbol. Used for multi-line parsing to detect annotation boundaries.

func UnescapeValue

func UnescapeValue(value string) string

UnescapeValue converts escape sequences to literal characters. Order matters: handle \\ first to avoid double-unescaping.

Types

type APIInfo

type APIInfo struct {
	// Title is the API title (required)
	Title string

	// Version is the API version (required)
	Version string

	// Description is the API description
	Description string

	// TermsOfService is the URL to the terms of service
	TermsOfService string

	// Contact contains contact information
	Contact *Contact

	// License contains license information
	License *License

	// Servers is the list of server configurations
	Servers []*Server

	// SecuritySchemes defines available security schemes
	SecuritySchemes map[string]*SecurityScheme

	// Security defines default security requirements
	Security [][]*SecurityRequirement // Array of arrays for OR/AND logic

	// Tags defines API-level tag definitions
	Tags []*Tag

	// DefaultContentType is the default content type for requests/responses
	DefaultContentType string
}

APIInfo represents the @api annotation

type BindTarget

type BindTarget struct {
	// Wrapper is the wrapper schema name (e.g., "DataResponse")
	Wrapper string

	// Field is the field to bind the body to (e.g., "Data")
	Field string
}

BindTarget represents @bind Wrapper.Field syntax

func ParseBindTarget

func ParseBindTarget(value string) *BindTarget

ParseBindTarget parses a @bind value into a BindTarget Format: "Wrapper.Field" (e.g., "DataResponse.Data")

type Body

type Body struct {
	// Schema is the schema name being referenced (e.g., "User", "[]User", "map[string]User")
	Schema string

	// Bind specifies the wrapper and field for envelope responses
	// e.g., @bind DataResponse.Data
	Bind *BindTarget
}

Body represents a @body annotation with optional binding

type CommentBlock

type CommentBlock struct {
	// Lines are the comment lines with // prefix removed and trimmed
	Lines []string

	// Position is the file position for error reporting
	Position token.Position
}

CommentBlock represents a block of comments extracted from the AST

func (*CommentBlock) GetAnnotationLines

func (cb *CommentBlock) GetAnnotationLines() []string

GetAnnotationLines returns all lines that are part of an annotation This includes the annotation line and any continuation lines

func (*CommentBlock) HasAnnotation

func (cb *CommentBlock) HasAnnotation(annotation string) bool

HasAnnotation checks if a comment block contains an annotation

func (*CommentBlock) String

func (cb *CommentBlock) String() string

String returns the comment block as a formatted string for debugging

type Contact

type Contact struct {
	Name  string
	Email string
	URL   string
}

Contact represents contact information

type Endpoint

type Endpoint struct {
	// FuncName is the Go function name (for inline declaration lookup)
	FuncName string

	// Method is the HTTP method (GET, POST, PUT, DELETE, etc.)
	Method string

	// Path is the URL path (e.g., /users/{id})
	Path string

	// OperationID is the operation ID
	OperationID string

	// Summary is a short summary
	Summary string

	// Description is a detailed description
	Description string

	// Tags are endpoint tags
	Tags []string

	// Deprecated indicates if the endpoint is deprecated
	Deprecated bool

	// Auth is the security scheme to use (overrides API default)
	Auth string

	// PathParams are the path parameter struct references
	PathParams []string

	// QueryParams are the query parameter struct references
	QueryParams []string

	// HeaderParams are the header parameter struct references
	HeaderParams []string

	// CookieParams are the cookie parameter struct references
	CookieParams []string

	// Request is the request body definition
	Request *RequestBody

	// Responses are the response definitions
	Responses map[string]*Response // Key is status code
}

Endpoint represents an @endpoint annotated function

type Field

type Field struct {
	// Name is the field name (from json/query/path/header/cookie tag)
	Name string

	// GoName is the Go field name
	GoName string

	// GoType is the Go type name
	GoType string

	// Required indicates if the field is required
	Required bool

	// Nullable indicates if the field is nullable (pointer type)
	Nullable bool

	// Description is the field description
	Description string

	// Format is the field format (email, uuid, date-time, etc.)
	Format string

	// Example is an example value
	Example string

	// Enum is a list of allowed values
	Enum []string

	// Default is the default value
	Default string

	// Minimum is the minimum value (for numbers)
	Minimum *float64

	// Maximum is the maximum value (for numbers)
	Maximum *float64

	// MinLength is the minimum length (for strings)
	MinLength *int

	// MaxLength is the maximum length (for strings)
	MaxLength *int

	// MinItems is the minimum number of items (for arrays)
	MinItems *int

	// MaxItems is the maximum number of items (for arrays)
	MaxItems *int

	// UniqueItems indicates array items must be unique
	UniqueItems bool

	// Pattern is a regex pattern (for strings)
	Pattern string

	// Deprecated indicates if the field is deprecated
	Deprecated bool
}

Field represents a struct field with @field annotation

type FuncInlineInfo

type FuncInlineInfo struct {
	// Query is the inline query parameter struct
	Query *InlineStructInfo

	// Path is the inline path parameter struct
	Path *InlineStructInfo

	// Header is the inline header parameter struct
	Header *InlineStructInfo

	// Cookie is the inline cookie parameter struct
	Cookie *InlineStructInfo

	// Request is the inline request body struct
	Request *InlineStructInfo

	// Responses are the inline response body structs keyed by status code
	Responses map[string]*InlineStructInfo
}

FuncInlineInfo contains inline declarations extracted from a function body

type InlineStructInfo

type InlineStructInfo struct {
	// VarName is the variable or type name
	VarName string

	// Annotation is the annotation type (query, path, header, cookie, request, response)
	Annotation string

	// Comment is the parsed comment block containing annotations
	Comment *CommentBlock

	// StructType is the AST struct type for field extraction
	StructType *ast.StructType

	// Ident is the AST identifier for type resolution via TypesInfo.Defs
	Ident *ast.Ident

	// StatusCode is the response status code (for response only)
	StatusCode string

	// FieldComments are the comments for struct fields
	FieldComments map[string]*CommentBlock
}

InlineStructInfo contains AST information for an inline struct declaration

type License

type License struct {
	Name string
	URL  string
}

License represents license information

type PackageComments

type PackageComments struct {
	// Name is the package name
	Name string

	// Pkg is the loaded package (needed for type resolution of inline declarations)
	Pkg *packages.Package

	// Package-level comments (for @api)
	PackageComments *CommentBlock

	// Struct-level comments (for @schema, @path, @query, @header, @cookie)
	StructComments map[string]*CommentBlock // Key: struct name

	// Field-level comments (for @field)
	FieldComments map[string]map[string]*CommentBlock // Key: struct name -> field name

	// Function-level comments (for @endpoint)
	FunctionComments map[string]*CommentBlock // Key: function name

	// TypeInfo contains metadata about type declarations
	TypeInfo map[string]*TypeDeclInfo // Key: type name

	// FuncInlines contains inline struct declarations within function bodies
	FuncInlines map[string]*FuncInlineInfo // Key: function name
}

PackageComments represents all comments extracted from a package

func ExtractComments

func ExtractComments(packagePath string) (*PackageComments, error)

ExtractComments extracts all comment blocks from a Go package

func (*PackageComments) GetFieldComment

func (pc *PackageComments) GetFieldComment(structName, fieldName string) *CommentBlock

GetFieldComment returns the comment block for a field

func (*PackageComments) GetFunctionComment

func (pc *PackageComments) GetFunctionComment(funcName string) *CommentBlock

GetFunctionComment returns the comment block for a function

func (*PackageComments) GetStructComment

func (pc *PackageComments) GetStructComment(structName string) *CommentBlock

GetStructComment returns the comment block for a struct

type Parameter

type Parameter struct {
	// Name is the struct name
	Name string

	// Type is the parameter type (path, query, header, cookie)
	Type ParameterType

	// GoTypeName is the full Go type name
	GoTypeName string

	// Fields are the parameter fields
	Fields []*Field
}

Parameter represents a parameter struct (@path, @query, @header, @cookie)

type ParameterType

type ParameterType string

ParameterType represents the type of parameter

const (
	PathParameter   ParameterType = "path"
	QueryParameter  ParameterType = "query"
	HeaderParameter ParameterType = "header"
	CookieParameter ParameterType = "cookie"
)

type ParsedAnnotation

type ParsedAnnotation struct {
	// Name is the annotation name (e.g., "@api", "@field")
	Name string

	// Metadata is extracted from the opening line for annotations with HasMetadata
	// Example: "@endpoint GET /users" -> "GET /users"
	// Example: "@server https://api.com" -> "https://api.com"
	Metadata string

	// Children are nested annotations
	Children map[string]*ParsedAnnotation

	// RepeatedChildren are children that can appear multiple times
	// Key is annotation name, value is slice of parsed annotations
	RepeatedChildren map[string][]*ParsedAnnotation

	// Value is the annotation value for ValueAnnotation types
	Value string

	// IsFlag indicates if this is a FlagAnnotation (e.g., @deprecated)
	IsFlag bool

	// Lines are the original comment lines for debugging
	Lines []string
}

ParsedAnnotation represents a parsed annotation with its content

func ParseAnnotationBlock

func ParseAnnotationBlock(lines []string, annotationName string, node *schema.SchemaNode) (*ParsedAnnotation, error)

ParseAnnotationBlock parses an annotation block using the schema

func ParseInlineAnnotation

func ParseInlineAnnotation(line, annotationName string, node *schema.SchemaNode) (*ParsedAnnotation, error)

ParseInlineAnnotation parses an inline annotation Example: @field { @description User email @format email } Note: All block annotations support inline format, but nested blocks are not allowed.

func (*ParsedAnnotation) GetChildValue

func (pa *ParsedAnnotation) GetChildValue(name string) string

GetChildValue returns the value of a child annotation

func (*ParsedAnnotation) GetRepeatedChildren

func (pa *ParsedAnnotation) GetRepeatedChildren(name string) []*ParsedAnnotation

GetRepeatedChildren returns all instances of a repeatable child

func (*ParsedAnnotation) HasChild

func (pa *ParsedAnnotation) HasChild(name string) bool

HasChild checks if a child annotation exists

type ParsedPackage

type ParsedPackage struct {
	// PackageName is the Go package name
	PackageName string

	// API contains the @api annotation data
	API *APIInfo

	// Schemas contains all @schema annotated structs
	Schemas map[string]*Schema

	// Parameters contains all parameter structs (@path, @query, @header, @cookie)
	Parameters map[string]*Parameter

	// Endpoints contains all @endpoint annotated functions
	Endpoints []*Endpoint
}

ParsedPackage represents a complete parsed Go package with all annotations

type Parser

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

Parser orchestrates the parsing of a Go package into a ParsedPackage

func NewParser

func NewParser(packagePath string) *Parser

NewParser creates a new parser for the given package path

func (*Parser) Comments

func (p *Parser) Comments() *PackageComments

Comments returns the extracted package comments This should be called after Parse() to access inline declarations and the loaded package

func (*Parser) Parse

func (p *Parser) Parse() (*ParsedPackage, error)

Parse parses the package and returns a ParsedPackage

type RequestBody

type RequestBody struct {
	// ContentType is the content type (json, xml, form, etc.)
	ContentType string

	// Body is the body definition with optional bindings
	Body *Body
}

RequestBody represents a request body

type Response

type Response struct {
	// StatusCode is the HTTP status code (200, 404, etc.)
	StatusCode string

	// ContentType is the content type
	ContentType string

	// Body is the body definition with optional bindings
	Body *Body

	// Description is the response description
	Description string

	// HeaderParams are the response header struct references
	HeaderParams []string
}

Response represents a response definition

type Schema

type Schema struct {
	// Name is the struct name
	Name string

	// GoTypeName is the full Go type name (for resolution)
	GoTypeName string

	// Description is the schema description
	Description string

	// Deprecated indicates if the schema is deprecated
	Deprecated bool

	// Fields are the struct fields
	Fields []*Field

	// IsGeneric indicates this is a generic struct (has type parameters)
	// Generic structs are templates and not emitted to components
	IsGeneric bool

	// IsTypeAlias indicates this is a type alias (e.g., type X = Y[Z])
	// Type aliases that instantiate generics are emitted to components
	IsTypeAlias bool

	// AliasOf is the type this aliases (for type aliases)
	AliasOf string
}

Schema represents a @schema annotated struct

type SecurityRequirement

type SecurityRequirement struct {
	SchemeName string
	Scopes     []string // For OAuth2
}

SecurityRequirement represents a security requirement

type SecurityScheme

type SecurityScheme struct {
	Name          string // Name of the scheme
	Type          string // http, apiKey, oauth2, openIdConnect
	Scheme        string // For http type: bearer, basic
	BearerFormat  string // For bearer scheme: JWT, etc.
	In            string // For apiKey: header, query, cookie
	ParameterName string // For apiKey: parameter name
	Description   string
}

SecurityScheme represents a security scheme definition

type Server

type Server struct {
	URL         string
	Description string
}

Server represents a server configuration

type Tag

type Tag struct {
	// Name is the tag name
	Name string

	// Description is the tag description
	Description string
}

Tag represents an API tag definition

type TypeDeclInfo

type TypeDeclInfo struct {
	Name        string
	IsGeneric   bool   // Has type parameters (e.g., type Foo[T any] struct{})
	IsTypeAlias bool   // Is a type alias (e.g., type Bar = Foo[Baz])
	AliasOf     string // For type aliases, the aliased type (e.g., "Foo[Baz]")
}

TypeDeclInfo contains metadata about a type declaration

Jump to

Keyboard shortcuts

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