codegen

package
v0.6.0 Latest Latest
Warning

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

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

Documentation

Overview

Package codegen turns a parsed .pzl template (constellation/doc/DOC-COMPILER-DESIGN.md §c) into the generated JS module — the user's <script> emitted VERBATIM plus an injected runtime import and an appended `Name.prototype.render = function () {…}` (constellation/doc/DOC-COMPILER-DESIGN.md §d, constellation/doc/DOC-APP-ANATOMY.md §1). The correctness anchor is the Phase 1 hand-written fixture tests/fixtures/todos/Home.compiled.js (D14): this codegen reproduces its render function mechanically.

Formatting is byte-exact against the fixture; the golden-file harness (golden_test.go) is a byte-compare. The idioms are documented inline where they are emitted.

Whitespace / text policy (derived from Home.pzl vs Home.compiled.js)

Applied to template Text nodes only (never to attribute values, which keep their bytes). For each Text node:

  • collapse every run of ASCII whitespace to a single space;
  • strip the leading space if the original leading whitespace run contained a newline (i.e. it was source indentation); strip the trailing space likewise;
  • if the result is empty, drop the node.

So "\n Made with " → "Made with " (indentation gone, the space before the next inline element kept) and pure inter-element indentation ("</h2>\n <form>") drops entirely. Consecutive Text/Interpolation siblings coalesce into ONE text vnode whose value is the `+`-concatenation of quoted literals and shared display-coercion calls.

Index

Constants

View Source
const SVGAssetSpecifierPrefix = "@magic-spells/puzzle/svg-asset/"

SVGAssetSpecifierPrefix is the import-specifier prefix for a {#svg} shared asset module: the use-site import is `<prefix><app/assets-relative src>` (e.g. "@magic-spells/puzzle/svg-asset/icons/heart.svg"). The esbuild plugin owns resolving it to the file on disk and serving the factory module (dedup mode); pzlc standalone never emits it (it inlines).

Variables

This section is empty.

Functions

func SVGAssetModule

func SVGAssetModule(data []byte, filename, viewNodeImport string) (string, error)

SVGAssetModule builds the JS source of a shared {#svg} asset module from a resolved SVG file's bytes: it scans the single <svg> root (same ScanSVGFile the inline path uses, so the vnode is identical) and emits a factory that returns a fresh island-frozen `<svg>` vnode on each call. viewNodeImport is the module specifier to import ViewNode from (the runtime's index). filename positions any malformed-file error inside the svg. The factory takes an optional `key` so a dedup use site inside a {#for} still reconciles by key.

func SVGAssetModuleFrom added in v0.6.0

func SVGAssetModuleFrom(s *ScannedSVG, filename, viewNodeImport string) (string, error)

SVGAssetModuleFrom builds the same module from an ALREADY-scanned asset, so a plugin that shares codegen's SVGCache does not re-read and re-parse a file the .pzl compile already validated in this build. A scan error is returned unchanged — it is the same positioned *parser.ParseError SVGAssetModule would have produced.

func ScopeID

func ScopeID(filename string) string

ScopeID derives the stable per-file scope id for <style scoped> (v1.27, D59): `pzl-` + 8 lowercase hex chars of FNV-1a-32 over the compiler-relative, forward-slash-normalized source path. It is the SINGLE source of the id — both the codegen root stamp (data-<id>) and the esbuild plugin's @scope CSS wrapper call this so the attribute and the rule always agree. Path-derived, so it is byte-stable across machines (golden reproducibility) and only changes when the .pzl is renamed (the stamp and CSS move together in the same build, D59).

func ValidSVGPath added in v0.4.0

func ValidSVGPath(src string) bool

ValidSVGPath is the exported form of validSVGPath, for callers outside this package that resolve a {#svg} asset specifier against app/assets/ — the esbuild plugin validates the virtual-module specifier with the SAME rule the compile-time path uses, before it ever touches the filesystem.

Types

type EmissionMode

type EmissionMode int

EmissionMode selects the render root shape (constellation/doc/DOC-DECISIONS.md D20).

const (
	// ModeView emits a real <puzzle-view> root element carrying the template's
	// attributes — for files under app/views/** and app/layouts/**.
	ModeView EmissionMode = iota
	// ModeComponent renders inline: the render() returns the template's single
	// root element with no wrapper, and attributes on <puzzle-view> are an error.
	ModeComponent
)

func ModeForPath

func ModeForPath(path string) EmissionMode

ModeForPath applies the D20 directory convention: app/views/** and app/layouts/** compile as views; everything else is a reusable component.

type Options

type Options struct {
	Filename string
	Mode     EmissionMode

	// ModulePath is the app-root-relative, forward-slashed path of the source
	// .pzl (e.g. "app/views/Home.pzl"), stamped onto the compiled class as
	// `Class.__pzlModule = "<path>"` so the static-pages build (D81) can map a
	// route's view/layout classes back to their source modules for per-page entry
	// generation. The esbuild plugin threads its app-relative `name` in here.
	// Empty means "no app root is known" (the standalone pzlc single-file path and
	// the codegen goldens): the stamp then falls back to the plain basename of
	// Filename.
	ModulePath string
	// AssetsDir is the absolute (or test-relative) path of the app's assets dir
	// ({#svg} paths resolve from here, v1.14 D46). Empty means "not configured":
	// any {#svg} then fails with a "this project has no app/assets/ directory"
	// error.
	AssetsDir string

	// SVGDedup selects the dedup emission for {#svg} (v1.14 D46 amendment): each
	// use site becomes a call to a per-asset shared factory imported from a
	// virtual module (`@magic-spells/puzzle/svg-asset/<src>`) that the esbuild
	// plugin resolves + serves, so esbuild stores each unique icon ONCE across the
	// bundle. The plugin sets this true. Left false (pzlc standalone, no bundler),
	// codegen inlines the markup at every use site as before — a self-contained
	// module with no unresolved virtual imports.
	SVGDedup bool

	// SVGCache memoizes {#svg} asset reads + scans across every file compiled in
	// one build (svgcache.go). The esbuild plugin creates one per build and shares
	// it with its shared-asset module loader; left nil, every use site reads and
	// scans its file exactly as before.
	SVGCache *SVGCache
}

Options configure a compile.

type Result

type Result struct {
	JS           string
	InlinedFiles []string
	// Warnings are non-fatal codegen diagnostics (v0.1 hardening): a template
	// expression that references a <script> import, which resolveExpr rewrites to
	// __d.<name> → undefined at render (SPEC §6). Out-of-band — the generated JS is
	// unaffected, so goldens never move. The plugin/pzlc print them to stderr.
	Warnings []Warning
}

Result is the output of Compile: the generated module JS and the absolute (or as-joined) paths of every file inlined via {#svg} (deduped + sorted, v1.14 D46). InlinedFiles is populated even when Compile returns an error — a missing svg's attempted path is recorded so the plugin can hand it to esbuild as a WatchFile, invalidating the cached failure once the file appears.

func Compile

func Compile(sec *parser.Sections, opts Options) (*Result, error)

Compile splits are already done by the caller: it takes the Sections (scripts + template attrs) and produces the full generated module string plus the list of {#svg}-inlined files (Result). The template is parsed here so parse and codegen share one entry point. The returned *Result is always non-nil — even on error, so InlinedFiles (the {#svg} paths seen so far) is available to the caller for esbuild WatchFiles.

type SVGCache added in v0.6.0

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

SVGCache memoizes ScannedSVG per (absolute path, diagnostic name) for the lifetime of one build. The name is part of the key because it is baked into ScanErr's position; in practice every caller derives the same "app/assets/<src>" name for a given file, so the second component only ever splits the key if that ever stops being true — in which case both entries are correct rather than one being subtly wrong.

A nil *SVGCache is the valid "no memo" value: Load then reads and scans directly. That is what the standalone pzlc path and the codegen goldens use.

func NewSVGCache added in v0.6.0

func NewSVGCache() *SVGCache

NewSVGCache returns an empty memo.

func (*SVGCache) Evict added in v0.6.0

func (c *SVGCache) Evict(paths []string)

Evict drops the memo for every key naming one of paths. It exists for the long-lived dev caches (a `puzzle dev` session keeps ONE cache across rebuilds), where the file this memo describes genuinely can change: unlike the .pzl transform memo, whose key carries a content hash, this one is keyed by path alone, so an edited icon would otherwise be served from the entry made before the edit — and, worse, the .pzl that inlines it hashes the same, so nothing else would notice. Callers evict on any change to a watched file and pay at most one re-read.

func (*SVGCache) Load added in v0.6.0

func (c *SVGCache) Load(full, name string) *ScannedSVG

Load returns the scan for full, reading and parsing it at most once per key. It never returns nil.

type ScannedSVG added in v0.6.0

type ScannedSVG struct {
	Data  []byte
	Attrs []parser.Attr
	Inner string
	// ReadErr is set when the file could not be read at all. The CALLER turns
	// this into its own positioned message (the .pzl's {#svg} site, or an
	// esbuild message for the virtual module), so the memo never has to know
	// which caller it is serving.
	ReadErr error
	// ScanErr is the malformed-file *parser.ParseError, already positioned
	// inside the SVG by ScanSVGFile.
	ScanErr error
}

ScannedSVG is one resolved {#svg} asset: the file's bytes and the result of scanning its single <svg> root. Treated as immutable after publication — consumers copy Attrs before splicing it into an AST, since the AST owner may append to that slice.

type Warning

type Warning struct {
	File    string
	Line    int
	Col     int
	Message string
}

Warning is a positioned, non-fatal codegen diagnostic. See Result.Warnings.

Jump to

Keyboard shortcuts

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