compiler

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const Version = "0.1.6"

Version is the compiler version, emitted in generated files as "// Compiler version: ...". Bump this constant when cutting a release (e.g. 0.1.0 → 0.2.0). Optionally override at build time so the released binary matches the tag: go build -ldflags "-X github.com/andriyg76/go-hbars/internal/compiler.Version=v0.2.0" ./cmd/hbc

Variables

This section is empty.

Functions

func AllContextTypeNames

func AllContextTypeNames(goName string, tree *typeNode) []string

AllContextTypeNames returns all context interface names that would be emitted from this template's type tree. Used to map each context type to its owning template (e.g. MainOrdersOrderItemContext -> "main").

func CollectPartialParamTypes

func CollectPartialParamTypes(parsed map[string][]ast.Node, names []string, funcNames map[string]string, helperExprs map[string]string) (map[string]string, map[string]bool)

CollectPartialParamTypes returns for each partial the context type to use for its render param. Only same-scope calls ({{> name}} with no expr) contribute. Returns (result, hashOnlyPartials); hashOnlyPartials[name]==true means that partial is only ever called with hash (e.g. {{> menu menu=...}}).

func CompileTemplates

func CompileTemplates(templates map[string]string, opts Options) ([]byte, error)

CompileTemplates compiles templates into Go source code. When opts.MaxPhase > 0, compilation runs in phases up to MaxPhase and writes requested phase outputs (Phase1Output, etc.); returns generated Go when MaxPhase is Phase4.

func LoadTemplates added in v0.1.5

func LoadTemplates(input string) (map[string]string, map[string]string, error)

LoadTemplates loads all .hbs files from a directory recursively, or a single .hbs file. Template names use slash-separated paths without the extension.

func RootFieldKeys

func RootFieldKeys(tree *typeNode) []string

RootFieldKeys returns root-level field names from the type tree (keys used at root context).

func RunPhase4 added in v0.1.2

func RunPhase4(phase1 *Phase1Result, phase2b *Phase2bResult, opts Options) ([]byte, error)

RunPhase4 emits Go source from phase results (uses phase1 and phase2b to drive existing codegen).

func RunPhased added in v0.1.2

func RunPhased(templates map[string]string, opts Options) (goSource []byte, err error)

RunPhased runs phases 1 through opts.MaxPhase, writes requested phase outputs, and returns the generated Go source when MaxPhase is Phase4. If MaxPhase is 0, RunPhased is not used.

func SharedPartialInfo added in v0.1.1

func SharedPartialInfo(typeSet map[string]map[string]bool, names []string, funcNames map[string]string) (canonicalType, primaryCaller map[string]string)

SharedPartialInfo returns for each shared partial (multiple same-scope callers) its canonical context type name and the primary caller template name (first alphabetically). Used so the compiler can emit one canonical interface per partial and have non-primary callers use it; primary keeps an embedding interface.

Types

type ASTNodeDTO added in v0.1.2

type ASTNodeDTO struct {
	Kind        string       `json:"kind"`
	Value       string       `json:"value,omitempty"`
	Expr        *ExprDTO     `json:"expr,omitempty"`
	Raw         bool         `json:"raw,omitempty"`
	Name        string       `json:"name,omitempty"`
	NameExpr    *ExprDTO     `json:"nameExpr,omitempty"`
	CtxExpr     *ExprDTO     `json:"ctxExpr,omitempty"`
	Unless      bool         `json:"unless,omitempty"`
	Test        *ExprDTO     `json:"test,omitempty"`
	Collection  *ExprDTO     `json:"collection,omitempty"`
	WithValue   *ExprDTO     `json:"withValue,omitempty"`
	Params      []ExprDTO    `json:"params,omitempty"`
	Hash        []HashDTO    `json:"hash,omitempty"`
	BlockParams []string     `json:"blockParams,omitempty"`
	Body        []ASTNodeDTO `json:"body,omitempty"`
	Else        []ASTNodeDTO `json:"else,omitempty"`
}

ASTNodeDTO is a JSON-serializable representation of ast.Node.

type CompilerLogger added in v0.1.2

type CompilerLogger interface {
	Info(format string, args ...any)
	Debug(format string, args ...any)
	Trace(format string, args ...any)
}

CompilerLogger is used for trace/verbose output. Pass via Options.Log; nil means no logging.

type ContextTypeName added in v0.1.2

type ContextTypeName string

ContextTypeName is a Go context interface name (e.g. "MainContext").

type ExprDTO added in v0.1.3

type ExprDTO struct {
	Kind   string    `json:"kind"`
	Value  string    `json:"value,omitempty"`
	Callee string    `json:"callee,omitempty"`
	Params []ExprDTO `json:"params,omitempty"`
	Hash   []HashDTO `json:"hash,omitempty"`
}

ExprDTO is a JSON-serializable representation of ast.Expr.

type GoIdent added in v0.1.2

type GoIdent string

GoIdent is the Go identifier for a template (e.g. "Main", "LayoutHeader").

type HashDTO added in v0.1.3

type HashDTO struct {
	Key   string  `json:"key"`
	Value ExprDTO `json:"value"`
}

HashDTO is a JSON-serializable key=value pair.

type Helper added in v0.1.2

type Helper string

Helper is a helper name (e.g. "upper", "lookup").

type HelperRef

type HelperRef struct {
	ImportPath string
	Ident      string
}

HelperRef points to a helper implementation.

type IRContextData added in v0.1.2

type IRContextData struct {
	Template Template
	GoName   GoIdent
	Fields   []IRDataField
	Comment  string
}

IRContextData describes one context data struct to emit.

type IRContextIface added in v0.1.2

type IRContextIface struct {
	Template Template
	GoName   GoIdent
	Methods  []IRIfaceMethod
	Comment  string
}

IRContextIface describes one context interface to emit.

type IRDataField added in v0.1.2

type IRDataField struct {
	FieldPath string
	Type      ContextTypeName
}

IRDataField is a field in a context data struct.

type IRIfaceMethod added in v0.1.2

type IRIfaceMethod struct {
	FieldPath   string
	ReturnType  ContextTypeName
	IsCanonical bool
}

IRIfaceMethod is a method on a context interface (field path -> return type).

type IRPartial added in v0.1.2

type IRPartial struct {
	Name      Template
	GoName    GoIdent
	CtxType   ContextTypeName
	FromMapFn string
}

IRPartial describes one partial entry in the partials map.

type IRRenderFunc added in v0.1.2

type IRRenderFunc struct {
	Template        Template
	GoName          GoIdent
	RootContext     ContextTypeName
	UseLayoutBlocks bool
}

IRRenderFunc describes one render function (renderX, RenderX, RenderXString, etc.).

type ImportSpecJSON added in v0.1.2

type ImportSpecJSON struct {
	Path string `json:"path"`
	Name string `json:"name,omitempty"`
}

ImportSpecJSON is the JSON shape for an import (path + optional name).

type MaxPhase added in v0.1.2

type MaxPhase int

MaxPhase limits how far compilation runs (1 through 4). Phase 2 is split into 2a and 2b internally.

const (
	Phase1  MaxPhase = 1 // Parsing only
	Phase2a MaxPhase = 2 // Partial/context types (2a)
	Phase2b MaxPhase = 3 // Type trees (2b)
	Phase3  MaxPhase = 4 // IR build
	Phase4  MaxPhase = 5 // Go codegen
)

type Options

type Options struct {
	PackageName       string
	RuntimeImport     string
	Helpers           map[string]HelperRef
	GenerateBootstrap bool   // Generate bootstrap code for server/processor
	GeneratorVersion  string // If set, emitted in generated file as "// Generator version: ..."
	// TemplateFiles maps template name (key in templates map) to source file path for error messages.
	// If set, compiler errors include file path and line number (e.g. "main.hbs:5: parser: unclosed block").
	TemplateFiles map[string]string

	// Phased compilation: when MaxPhase >= 1, compilation runs from phase 1 up to MaxPhase.
	// Non-empty output paths cause that phase's result to be written (JSON or .go).
	MaxPhase      MaxPhase
	Phase1Output  string // e.g. "phase1_ast.json"
	Phase2aOutput string
	Phase2bOutput string
	Phase3Output  string
	Phase4Output  string // final .go file path
	Log           CompilerLogger
}

Options configures code generation.

type PartialName added in v0.1.2

type PartialName string

PartialName is a partial/template name when used as a partial (may equal Template for root templates).

type Phase1Result added in v0.1.2

type Phase1Result struct {
	Templates     map[Template][]ast.Node
	Names         []Template
	FuncNames     map[Template]GoIdent
	HelperExprs   map[Helper]string
	HelperImports []importSpec
	UsedHelpers   []Helper
	TemplateFiles map[Template]string
}

Phase1Result is the output of phase 1 (parsing).

func RunPhase1 added in v0.1.2

func RunPhase1(templates map[string]string, opts Options) (*Phase1Result, error)

RunPhase1 parses templates and returns Phase1Result.

func (*Phase1Result) MarshalJSON added in v0.1.2

func (p *Phase1Result) MarshalJSON() ([]byte, error)

MarshalJSON for Phase1Result so phase output can encode it via DTO.

func (*Phase1Result) ToDTO added in v0.1.2

func (p *Phase1Result) ToDTO() Phase1ResultDTO

ToDTO converts Phase1Result to Phase1ResultDTO for JSON.

type Phase1ResultDTO added in v0.1.2

type Phase1ResultDTO struct {
	Templates     map[string][]ASTNodeDTO `json:"templates"`
	Names         []string                `json:"names"`
	FuncNames     map[string]string       `json:"funcNames"`
	HelperExprs   map[string]string       `json:"helperExprs,omitempty"`
	UsedHelpers   []string                `json:"usedHelpers,omitempty"`
	TemplateFiles map[string]string       `json:"templateFiles,omitempty"`
}

Phase1ResultDTO is the JSON shape for Phase1Result.

type Phase2aResult added in v0.1.2

type Phase2aResult struct {
	PartialParamTypes map[PartialName]ContextTypeName
	HashOnlyPartials  map[string]bool // partial names only ever called with hash (e.g. {{> menu menu=...}})
	TypeSet           map[PartialName]map[ContextTypeName]bool
	CanonicalType     map[PartialName]ContextTypeName
	PrimaryCaller     map[PartialName]Template
	// FuncNames may be extended for shared partials; pass through from Phase1.
	FuncNames map[PartialName]GoIdent
}

Phase2aResult is the output of phase 2a (partial/context type analysis).

func RunPhase2a added in v0.1.2

func RunPhase2a(phase1 *Phase1Result, opts Options) (*Phase2aResult, error)

RunPhase2a computes partial/context type analysis from Phase1Result.

func (*Phase2aResult) MarshalJSON added in v0.1.2

func (p *Phase2aResult) MarshalJSON() ([]byte, error)

MarshalJSON for Phase2aResult.

func (*Phase2aResult) ToDTO added in v0.1.2

func (p *Phase2aResult) ToDTO() Phase2aResultDTO

ToDTO converts Phase2aResult to Phase2aResultDTO for JSON.

type Phase2aResultDTO added in v0.1.2

type Phase2aResultDTO struct {
	PartialParamTypes map[string]string   `json:"partialParamTypes"`
	TypeSet           map[string][]string `json:"typeSet"`
	CanonicalType     map[string]string   `json:"canonicalType"`
	PrimaryCaller     map[string]string   `json:"primaryCaller"`
	FuncNames         map[string]string   `json:"funcNames"`
}

Phase2aResultDTO is the JSON shape for Phase2aResult.

type Phase2bResult added in v0.1.2

type Phase2bResult struct {
	Phase2a         *Phase2aResult
	TypeTrees       map[Template]*typeNode
	ContextToTmpl   map[ContextTypeName]Template
	EmitOrder       []Template
	NeedFmt         bool
	UseLayoutBlocks bool
}

Phase2bResult is the output of phase 2b (type trees per template).

func RunPhase2b added in v0.1.2

func RunPhase2b(phase1 *Phase1Result, phase2a *Phase2aResult, opts Options) (*Phase2bResult, error)

RunPhase2b builds type trees for each template.

func (*Phase2bResult) MarshalJSON added in v0.1.2

func (p *Phase2bResult) MarshalJSON() ([]byte, error)

MarshalJSON for Phase2bResult.

func (*Phase2bResult) ToDTO added in v0.1.2

func (p *Phase2bResult) ToDTO() Phase2bResultDTO

ToDTO converts Phase2bResult to Phase2bResultDTO for JSON.

type Phase2bResultDTO added in v0.1.2

type Phase2bResultDTO struct {
	TypeSet         map[string][]string    `json:"typeSet"`
	TypeTrees       map[string]TypeNodeDTO `json:"typeTrees"`
	EmitOrder       []string               `json:"emitOrder"`
	NeedFmt         bool                   `json:"needFmt"`
	UseLayoutBlocks bool                   `json:"useLayoutBlocks"`
}

Phase2bResultDTO is the JSON shape for Phase2bResult (type trees + metadata).

type Phase3Result added in v0.1.2

type Phase3Result struct {
	PackageName       string
	RuntimeImport     string
	EmitOrder         []Template
	ContextIfaces     []IRContextIface
	ContextData       []IRContextData
	Partials          []IRPartial
	RenderFuncs       []IRRenderFunc
	UseLayoutBlocks   bool
	GenerateBootstrap bool
	HelperImports     []importSpec
}

Phase3Result is the structured IR (codegen plan) produced by phase 3.

func RunPhase3 added in v0.1.2

func RunPhase3(phase1 *Phase1Result, phase2b *Phase2bResult, opts Options) (*Phase3Result, error)

RunPhase3 builds the structured IR from Phase2bResult and Phase1Result.

func (*Phase3Result) MarshalJSON added in v0.1.2

func (p *Phase3Result) MarshalJSON() ([]byte, error)

MarshalJSON for Phase3Result.

func (*Phase3Result) ToDTO added in v0.1.2

func (p *Phase3Result) ToDTO() Phase3ResultDTO

ToDTO converts Phase3Result to Phase3ResultDTO for JSON.

type Phase3ResultDTO added in v0.1.2

type Phase3ResultDTO struct {
	PackageName       string           `json:"packageName"`
	RuntimeImport     string           `json:"runtimeImport"`
	EmitOrder         []string         `json:"emitOrder"`
	ContextIfaces     []IRContextIface `json:"contextIfaces"`
	ContextData       []IRContextData  `json:"contextData"`
	Partials          []IRPartial      `json:"partials"`
	RenderFuncs       []IRRenderFunc   `json:"renderFuncs"`
	UseLayoutBlocks   bool             `json:"useLayoutBlocks"`
	GenerateBootstrap bool             `json:"generateBootstrap"`
	HelperImports     []ImportSpecJSON `json:"helperImports"`
}

Phase3ResultDTO is the JSON shape for Phase3Result (IR).

type Template added in v0.1.2

type Template string

Template is a template name (key in templates map, e.g. "main", "layout/header").

type TypeNodeDTO added in v0.1.2

type TypeNodeDTO struct {
	Fields    map[string]TypeNodeDTO `json:"fields,omitempty"`
	SliceElem *TypeNodeDTO           `json:"sliceElem,omitempty"`
	IsSlice   bool                   `json:"isSlice,omitempty"`
}

TypeNodeDTO is the JSON shape for typeNode.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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