template

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: May 29, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromPlaceholder

func FromPlaceholder(identifier string) (string, bool)

FromPlaceholder extracts the capture name from a placeholder identifier. Returns the name and true if the identifier is a placeholder, or "" and false otherwise.

func IsPlaceholder

func IsPlaceholder(identifier string) bool

IsPlaceholder returns true if the identifier is a template placeholder.

func NewRecipe

func NewRecipe(opts ...RecipeOption) recipe.Recipe

NewRecipe creates a recipe.Recipe from declarative before/after templates.

Example:

s := template.Expr("s")
r := template.NewRecipe(
    template.RecipeName("org.openrewrite.golang.RemoveRedundantSprintf"),
    template.WithDisplayName("Remove redundant fmt.Sprintf"),
    template.WithBefore(fmt.Sprintf(`fmt.Sprintf("%%s", %s)`, s), template.Imports("fmt")),
    template.WithAfter(fmt.Sprintf(`%s`, s)),
    template.WithCaptures(s),
)

func ToPlaceholder

func ToPlaceholder(name string) string

ToPlaceholder converts a capture name to a valid Go identifier that can be used in scaffold source code. Example: "expr" -> "__plh_expr__"

Types

type BeforeOption

type BeforeOption func(*beforeSpec)

BeforeOption configures a single before-pattern.

func Imports

func Imports(pkgs ...string) BeforeOption

Imports adds required imports for a before or after template.

type Capture

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

Capture represents a named placeholder in a pattern or template. It defines what kind of AST subtree can be matched and optionally constrains the match by Go type name.

func Expr

func Expr(name string) *Capture

Expr creates a capture for an expression position.

func Ident

func Ident(name string) *Capture

Ident creates a capture for an identifier/name position.

func Stmt

func Stmt(name string) *Capture

Stmt creates a capture for a statement position.

func TypeExpr

func TypeExpr(name string) *Capture

TypeExpr creates a capture for a type position.

func (*Capture) IsVariadic

func (c *Capture) IsVariadic() bool

IsVariadic returns true if this capture matches zero or more items.

func (*Capture) Kind

func (c *Capture) Kind() CaptureKind

Kind returns the capture's syntactic kind.

func (*Capture) MaxCount

func (c *Capture) MaxCount() int

MaxCount returns the maximum number of items for variadic captures (-1 = unlimited).

func (*Capture) MinCount

func (c *Capture) MinCount() int

MinCount returns the minimum number of items for variadic captures.

func (*Capture) Name

func (c *Capture) Name() string

Name returns the capture's name.

func (*Capture) Placeholder

func (c *Capture) Placeholder() string

Placeholder returns the placeholder identifier used in scaffold source code.

func (*Capture) String

func (c *Capture) String() string

String returns the placeholder identifier, making Capture usable with fmt.Sprintf.

func (*Capture) TypeName

func (c *Capture) TypeName() string

TypeName returns the optional Go type constraint.

func (*Capture) Variadic

func (c *Capture) Variadic(min, max int) *Capture

Variadic returns a copy of the capture configured to match multiple items. min and max set bounds (-1 for max means unlimited).

func (*Capture) WithType

func (c *Capture) WithType(typeName string) *Capture

WithType returns a copy of the capture with a type constraint. The type name is used in the scaffold preamble for type-attributed matching.

type CaptureKind

type CaptureKind int

CaptureKind indicates the syntactic position a capture occupies.

const (
	CaptureExpression CaptureKind = iota // expression position (default)
	CaptureType                          // type position
	CaptureName                          // identifier/name position
	CaptureStatement                     // statement position
)

type GoPattern

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

GoPattern represents a parsed code pattern that can be matched against AST nodes. Patterns use placeholder identifiers (from Captures) that bind to matched subtrees.

func (*GoPattern) Match

func (p *GoPattern) Match(candidate java.J, cursor *visitor.Cursor) *MatchResult

Match attempts to match this pattern against the given candidate node. Returns a MatchResult containing captured bindings on success, or nil on failure.

func (*GoPattern) Matches

func (p *GoPattern) Matches(candidate java.J, cursor *visitor.Cursor) bool

Matches returns true if this pattern matches the candidate.

type GoTemplate

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

GoTemplate represents a parsed code template that can be applied to produce new AST nodes with captured values substituted in.

func (*GoTemplate) Apply

func (t *GoTemplate) Apply(cursor *visitor.Cursor, values *MatchResult) java.J

Apply produces a new AST node by parsing the template and substituting captured values from the MatchResult.

type MatchResult

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

MatchResult holds the captured AST nodes from a successful pattern match.

func NewMatchResult

func NewMatchResult() *MatchResult

NewMatchResult creates a MatchResult from binding pairs.

func (*MatchResult) Get

func (m *MatchResult) Get(name string) java.J

Get returns the single captured node for the given name, or nil if not bound.

func (*MatchResult) GetCapture

func (m *MatchResult) GetCapture(c *Capture) java.J

GetCapture returns the captured node for the given Capture, or nil.

func (*MatchResult) GetList

func (m *MatchResult) GetList(name string) []java.J

GetList returns the variadic captured nodes for the given name.

func (*MatchResult) Has

func (m *MatchResult) Has(name string) bool

Has returns true if a binding exists for the given capture name.

type PatternBuilder

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

PatternBuilder constructs a GoPattern with fluent configuration.

func Expression

func Expression(code string) *PatternBuilder

Expression creates a PatternBuilder for matching an expression.

func StatementPattern

func StatementPattern(code string) *PatternBuilder

Statement creates a PatternBuilder for matching a statement.

func TopLevel

func TopLevel(code string) *PatternBuilder

TopLevel creates a PatternBuilder for matching a top-level declaration.

func (*PatternBuilder) Build

func (b *PatternBuilder) Build() *GoPattern

Build creates the GoPattern.

func (*PatternBuilder) Captures

func (b *PatternBuilder) Captures(caps ...*Capture) *PatternBuilder

Captures adds captures to the builder.

func (*PatternBuilder) Imports

func (b *PatternBuilder) Imports(pkgs ...string) *PatternBuilder

Imports adds required imports for the pattern code.

type RecipeOption

type RecipeOption func(*templateRecipeConfig)

RecipeOption configures a template recipe via NewRecipe.

func AsExpression

func AsExpression() RecipeOption

AsExpression forces all templates to be parsed as expressions.

func AsStatement

func AsStatement() RecipeOption

AsStatement forces all templates to be parsed as statements.

func RecipeName

func RecipeName(name string) RecipeOption

RecipeName sets the fully qualified recipe name.

func WithAfter

func WithAfter(code string, opts ...BeforeOption) RecipeOption

WithAfter sets the after-template code.

func WithBefore

func WithBefore(code string, opts ...BeforeOption) RecipeOption

WithBefore adds a before-pattern. Can be called multiple times for Refaster anyOf-style matching (first match wins).

func WithCaptures

func WithCaptures(caps ...*Capture) RecipeOption

WithCaptures declares the capture placeholders used in templates.

func WithDescription

func WithDescription(desc string) RecipeOption

WithDescription sets the recipe description.

func WithDisplayName

func WithDisplayName(name string) RecipeOption

WithDisplayName sets the human-readable display name.

func WithTags

func WithTags(tags ...string) RecipeOption

WithTags sets categorization tags.

type RewriteVisitor

type RewriteVisitor struct {
	visitor.GoVisitor
	// contains filtered or unexported fields
}

RewriteVisitor applies a pattern match + template replacement on every node.

func Rewrite

func Rewrite(before *GoPattern, after *GoTemplate) *RewriteVisitor

Rewrite creates a visitor that matches the "before" pattern and replaces with the "after" template. This is a convenience for simple 1:1 rewrites.

func (*RewriteVisitor) Visit

func (v *RewriteVisitor) Visit(t java.Tree, p any) java.Tree

Visit overrides the default Visit to attempt pattern matching on every node.

type ScaffoldKind

type ScaffoldKind int

ScaffoldKind indicates what kind of Go construct the template represents.

const (
	ScaffoldExpression ScaffoldKind = iota // wraps in: var __v__ = <code>
	ScaffoldStatement                      // wraps in: func __f__() { <code> }
	ScaffoldTopLevel                       // wraps in: package __p__; <code>
)

type TemplateBuilder

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

TemplateBuilder constructs a GoTemplate with fluent configuration.

func ExpressionTemplate

func ExpressionTemplate(code string) *TemplateBuilder

ExpressionTemplate creates a TemplateBuilder for producing an expression.

func StatementTemplate

func StatementTemplate(code string) *TemplateBuilder

StatementTemplate creates a TemplateBuilder for producing a statement.

func TopLevelTemplate

func TopLevelTemplate(code string) *TemplateBuilder

TopLevelTemplate creates a TemplateBuilder for producing a top-level declaration.

func (*TemplateBuilder) Build

func (b *TemplateBuilder) Build() *GoTemplate

Build creates the GoTemplate.

func (*TemplateBuilder) Captures

func (b *TemplateBuilder) Captures(caps ...*Capture) *TemplateBuilder

Captures adds captures to the builder.

func (*TemplateBuilder) Imports

func (b *TemplateBuilder) Imports(pkgs ...string) *TemplateBuilder

Imports adds required imports for the template code.

type TemplateRecipe

type TemplateRecipe struct {
	recipe.Base
	// contains filtered or unexported fields
}

TemplateRecipe is an embeddable base type for struct-based template recipes. Embed it and call Init() to wire up the before/after patterns.

Example:

type MyRecipe struct {
    template.TemplateRecipe
}

func NewMyRecipe() *MyRecipe {
    s := template.Expr("s")
    r := &MyRecipe{}
    r.InitTemplate(
        template.WithBefore(fmt.Sprintf(`old(%s)`, s)),
        template.WithAfter(fmt.Sprintf(`new(%s)`, s)),
        template.WithCaptures(s),
    )
    return r
}

func (*TemplateRecipe) Editor

func (tr *TemplateRecipe) Editor() recipe.TreeVisitor

Editor returns the auto-generated visitor.

func (*TemplateRecipe) InitTemplate

func (tr *TemplateRecipe) InitTemplate(opts ...RecipeOption)

InitTemplate configures the template recipe with before/after patterns. Must be called before the recipe is used.

Jump to

Keyboard shortcuts

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