parser

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: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LexPlainEndsExpr

func LexPlainEndsExpr(c byte, prev bool) bool

LexPlainEndsExpr folds a single plain byte c (one LexSkip did NOT consume: operator, bracket, separator, digit, or whitespace) into prevEndsExpr. A digit or a closing )/]/} ends an expression; whitespace is insignificant and leaves the state unchanged; every other operator/delimiter means the next '/' opens a regex.

func LexSkip

func LexSkip(s string, i int, prevEndsExpr bool) (next int, pee bool, consumed bool)

LexSkip inspects the byte at s[i] for the balanced scanners. When it begins a lexical unit the caller must treat as OPAQUE — a '...'/"..."/`...` string, a /re/flags regex literal, a // or /* */ comment, an identifier run, or a ++/-- update operator — LexSkip returns the index just past that unit, the prevEndsExpr state that follows it, and consumed=true; the caller must NOT re-inspect the skipped bytes. For any other byte (operator, bracket, separator, digit, whitespace) it returns consumed=false and leaves i/pee alone: the caller processes s[i] itself, then folds it into prevEndsExpr via LexPlainEndsExpr.

Strings and template literals are escape-aware and close on the matching quote. Template `${…}` interiors are scanned with the same balanced machinery, so strings/comments/regexes/nested backticks inside an interpolation cannot expose a brace or section-close sentinel to the caller. An identifier run is consumed as a unit so a keyword that cannot end an expression (return/typeof/…) leaves a following '/' a regex, exactly as resolveExpr does; a keyword used as a property name (`.return`) still ends an expression. Identifier runs and strings contain no separators or brackets, so swallowing them whole never hides a separator/depth char from the caller.

Types

type Attr

type Attr interface {
	// contains filtered or unexported methods
}

Attr is an element attribute or component prop.

func ScanSVGFile

func ScanSVGFile(src []byte, filename string) (rootAttrs []Attr, inner string, err error)

ScanSVGFile lifts the single <svg> root from a resolved SVG file's bytes. It returns the root element's attributes (all literal StaticAttrs) and the verbatim inner markup between the open tag and the matching final </svg> (empty for a self-closing <svg/>). The inner markup is inert — it is NOT template-parsed. Errors are *ParseError with File=filename, positioned inside the svg so the plugin can point at the real spot.

type Case

type Case struct {
	Expr    string
	Clauses []WhenClause
	Else    []Node
	Pos     Position
}

Case is `{#case expr} {:when v1, v2} … {:when v3} … {:else} … {/case}` (Liquid-style multi-branch). Clauses are matched in declaration order with strict `===` against Expr; the first matching clause wins with NO fallthrough. Each WhenClause carries one or more OR-matched Values. Else is the optional trailing default branch (nil when absent). Unlike {#unless}, this does NOT desugar to If: codegen emits an IIFE that binds Expr to a temp ONCE, so a getter-backed data value is evaluated a single time.

type Component

type Component struct {
	Name     string
	Props    []Attr
	Children []Node
	Pos      Position
}

Component is a capitalized tag referencing an imported component. Props reuse the attribute node types; callback props (@name={...}) are EventAttr values resolved by codegen (D16).

type DynamicAttr

type DynamicAttr struct {
	Name string
	Expr string
	Pos  Position
}

DynamicAttr is `name={ expr }` — a single unquoted brace expression. Binding classification and the property-vs-attribute distinction are downstream compiler/runtime concerns.

type Element

type Element struct {
	Tag      string
	Attrs    []Attr
	Children []Node
	Pos      Position

	// ContainsRaw is set only on the synthetic template/skeleton root when its
	// source contained at least one D150 {#raw} block. The block body expands
	// into ordinary Text/Element nodes, so this preserves the exact source fact
	// needed by the build-wide usage scan.
	ContainsRaw bool

	// RawInner, when non-nil, carries a verbatim markup string that codegen
	// emits as the ViewNode's string children (island seed, D44) instead of
	// reconciled child vnodes — set only by codegen's {#svg} resolve pass
	// (v1.14, D46), which replaces an InlineSVG node with an <svg> Element whose
	// RawInner holds the inlined file's inner markup. nil for every parsed
	// element, so island-/svg-free templates are unaffected.
	RawInner *string

	// RawSrc carries the app/assets-relative source path of a resolved {#svg}
	// (e.g. "icons/heart.svg"), set alongside RawInner by codegen's resolve pass
	// (v1.14, D46). Empty for every parsed element. Codegen uses it in SVG-dedup
	// mode to key the per-asset shared module the use site imports rather than
	// inlining the markup at every site.
	RawSrc string
}

Element is an HTML element, including the <puzzle-view> root. Its attributes are preserved (they become the root ViewNode's attributes, not a hardcoded div).

func Parse

func Parse(source []byte, filename string) (*Element, error)

Parse splits sections and parses the template, returning the <puzzle-view> root element.

func ParseSkeleton

func ParseSkeleton(sec *Sections, filename string) (*Element, error)

ParseSkeleton parses the optional <puzzle-skeleton> section (v1.8, D39) with the full template grammar, returning (nil, nil) when the file has none. The synthetic root carries NO attributes — in view mode codegen re-parents the skeleton children under the same <puzzle-view> root (and attributes) as the real template, so the loaded swap patches children only.

func ParseTemplate

func ParseTemplate(sec *Sections, filename string) (*Element, error)

ParseTemplate parses the already-split template content into the root <puzzle-view> element (attributes supplied by the section splitter).

type ErrorList

type ErrorList []*ParseError

ErrorList is a batch of parse errors. The parser may collect more than one error per file to improve reporting, but any error means the parse failed — there is never a best-effort AST (constellation/doc/DOC-COMPILER-DESIGN.md §e).

func (ErrorList) Error

func (l ErrorList) Error() string

type EventAttr

type EventAttr struct {
	Name      string
	Modifiers []string
	Expr      string
	Pos       Position
}

EventAttr is `@name={ expr }` with optional `:modifier` suffixes (`@keydown:enter:prevent={ … }`). On a DOM element it is a listener; on a component tag codegen turns it into a callback prop (D16) and rejects any modifiers. Name is the bare event (excludes '@' and modifiers); Modifiers holds the validated modifier list in written order (empty when none).

type For

type For struct {
	Item       string
	Collection string
	IsRange    bool
	RangeFrom  string
	RangeTo    string
	Counter    string
	Body       []Node
	Pos        Position
}

For is `{#for item in collection}` or the range form `{#for from...to}` (IsRange). For the range form Item is empty and codegen uses the index. An optional trailing `, name` binds a loop counter (Counter, empty when absent): the 0-based index for the item form, the current number for the range form.

type FormatterCall

type FormatterCall struct {
	Name string
	Args []string
}

FormatterCall is one link in an interpolation's formatter chain. Args are raw JS expression strings (e.g. "'short'", "', '") emitted as-is by codegen; they participate in scope resolution like any other expression.

type If

type If struct {
	Cond string
	Then []Node
	Else []Node
	Pos  Position
}

If is `{#if cond} Then {:else} Else {/if}`. Else is nil when absent. v1 has no {:elsif}.

type InlineIfPart

type InlineIfPart struct {
	Cond string
	Then []Part
	Else []Part
	Pos  Position
}

InlineIfPart is `{#if cond} Then {:else} Else {/if}` inside an attribute value. Then/Else may contain only static text and interpolations — no elements and no {#for} (parse error otherwise).

type InlineSVG

type InlineSVG struct {
	Src    string
	SrcPos Position
	Pos    Position
}

InlineSVG is `{#svg 'icons/heart.svg'}` (v1.14, D46): the framework's first void block tag — self-contained, with no `{/svg}` closer. The referenced file is inlined at compile time by codegen, which reads it and splices an <svg> element carrying the file's root attrs and its inner markup as a raw seed string (island semantics, D44). The parser only records the request. Src is the quoted static path with its quotes stripped; SrcPos points at the path literal in the header (so codegen's missing-file error lands there); Pos is the `{#svg}` opener.

type InterpPart

type InterpPart struct {
	Interp *Interpolation
}

InterpPart is an interpolation inside an attribute value.

type Interpolation

type Interpolation struct {
	Expr       string
	Formatters []FormatterCall
	Pos        Position
}

Interpolation is `{ expr | fmt(args) | ... }`: a base expression plus an optional formatter chain.

type MixedAttr

type MixedAttr struct {
	Name  string
	Parts []Part
	Pos   Position
}

MixedAttr is a quoted attribute value that interleaves static text, interpolations, and inline {#if} blocks (constellation/doc/DOC-COMPILER-DESIGN.md §c attribute-value mini-grammar). Codegen concatenates the parts.

type Node

type Node interface {
	// contains filtered or unexported methods
}

Node is any template tree node.

type ParseError

type ParseError struct {
	File    string
	Line    int
	Col     int
	Message string
	// Note is optional supplementary guidance (e.g. a corrected-code example)
	// surfaced by the esbuild plugin as an api.Note under the error message.
	Note string
}

ParseError is the structured error type for the template parser (constellation/doc/DOC-COMPILER-DESIGN.md §e). It carries the file and 1-based line/column of the offending construct and implements error, so the esbuild plugin (Step 3) can surface it directly as an api.Message.

func (*ParseError) Error

func (e *ParseError) Error() string

type ParsedFile

type ParsedFile struct {
	Root      *Element
	Scripts   string
	Styles    string
	HasStyles bool
}

ParsedFile is the full result of parsing a .pzl file: the template root plus the opaque <script> body and optional <style> body.

func ParseFile

func ParseFile(source []byte, filename string) (*ParsedFile, error)

ParseFile parses a whole .pzl file.

type Part

type Part interface {
	// contains filtered or unexported methods
}

Part is one segment of a MixedAttr value.

type Portal added in v0.5.0

type Portal struct {
	Children []Node
	Pos      Position
}

Portal is a <Portal>…</Portal> teleport marker (D144). It takes no attributes and is paired-only; Children is the subtree the runtime mounts into the framework-created portal outlet instead of at this position.

type Position

type Position struct {
	Line   int
	Col    int
	Offset int
}

Position is a source location: 1-based line and column plus the 0-based byte offset into the ORIGINAL .pzl file. Positions are computed relative to the original file so that template parse errors report file-accurate coordinates even though the lexer only ever sees the <puzzle-view> content (see constellation/doc/DOC-COMPILER-DESIGN.md §c and §e).

Position lives in one place; every token and AST node carries one.

func (Position) Advance added in v0.4.0

func (p Position) Advance(s string) Position

Advance is advance for callers outside the parser: codegen maps a byte offset inside the opaque <script> body back to file coordinates by advancing the section's start position over the preceding bytes.

type Sections

type Sections struct {
	// TemplateContent is the inner content of <puzzle-view> (between '>' and
	// '</puzzle-view>').
	TemplateContent string
	// TemplateAttrs are the parsed attributes of the <puzzle-view> tag itself.
	TemplateAttrs []Attr
	// TemplatePos is where TemplateContent starts, so template parse errors
	// report file-accurate positions.
	TemplatePos Position
	// ViewTagPos is the position of the opening '<puzzle-view'.
	ViewTagPos Position

	// Skeleton is the inner content of the optional <puzzle-skeleton> section
	// (v1.8, D39), shown while the first data() is pending; HasSkeleton reports
	// whether one was present. The tag accepts exactly one OPTIONAL attribute,
	// `min-duration` (v1.20, D52) — every other attribute is a compile error.
	Skeleton       string
	HasSkeleton    bool
	SkeletonPos    Position
	SkeletonTagPos Position
	// SkeletonMinDuration is the anti-flash hold in ms parsed from
	// `<puzzle-skeleton min-duration="N">` (v1.20, D52); 0 when the attribute is
	// absent (or 0) — that case emits byte-identically to v1.8.
	SkeletonMinDuration int

	// Scripts is the opaque, byte-for-byte body of <script>.
	Scripts    string
	ScriptsPos Position
	// ScriptsLang is the normalized `lang` attribute of <script> (v1.22, D54):
	// "" for JavaScript (attribute absent, or lang="js") and "ts" for TypeScript
	// (lang="ts"). It only selects the esbuild loader for the generated module;
	// the Go compiler still treats the body as an opaque string and never parses
	// it. Any other lang value (or a second attribute) is a compile error.
	ScriptsLang string

	// Styles is the body of <style>; HasStyles reports whether one was present.
	Styles    string
	HasStyles bool
	StylesPos Position
	// StylesTagPos is the position of the opening '<style'.
	StylesTagPos Position
	// StylesScoped is the bare `scoped` attribute of <style> (v1.27, D59): true
	// opts the block into per-component scoping (the plugin wraps it in a native
	// @scope rule and codegen stamps the template root). It is the ONLY attribute
	// <style> accepts; absent → false, emitting global CSS byte-identically to
	// pre-v1.27. Any other attribute, a valued/dynamic scoped, or a duplicate is a
	// compile error.
	StylesScoped bool
}

Sections is the result of splitting a .pzl file.

func SplitSections

func SplitSections(src, filename string) (*Sections, error)

SplitSections splits src into its sections, tolerant of whitespace and order. A missing <puzzle-view>, or more than one of any section, is an error with a position (constellation/doc/DOC-COMPILER-DESIGN.md §b, §e). <script> is OPTIONAL (DOC-SPEC.md §4): a template-only .pzl leaves Scripts == "" and codegen synthesizes a PuzzleView subclass named from the filename.

type Slot

type Slot struct {
	Name     string
	Children []Node
	Pos      Position
}

Slot is a composition render target (D141). <Children> and bare <Slot> have an empty Name and substitute the default bucket; <Slot name="x"> carries a static, non-empty Name. Paired forms carry ordinary template Children that render as fallback content when the bucket is unfilled. Self-closing and empty paired forms have no fallback.

type StaticAttr

type StaticAttr struct {
	Name      string
	Value     string
	Valueless bool
	// LiteralName marks an attribute captured inside {#raw}, where the name is
	// authored markup rather than Puzzle grammar (D150). It suppresses every
	// directive reading of the name: `ref` is not validated or wired to
	// this.refs (refs.go, codegen), `island` does not mark a frozen subtree
	// (island.go), `key` does not suppress a synthetic {#for} key (codegen), and
	// an @-prefixed name gets the runtime-private vnode-key escape so the DOM
	// attribute is written as authored instead of binding a listener.
	LiteralName bool
	Pos         Position
}

StaticAttr is a plain string attribute (class="btn") or a valueless boolean attribute (autofocus → Value "", Valueless true). Valueless is what distinguishes the bare form from an EXPLICIT empty value (value="" → Value "", Valueless false): both leave Value empty, but codegen emits `true` for the bare form and `”` for the explicit one, and the island directive (D44) accepts only the bare form. Valueless is the ONE way to ask "was this attr written without an =value?" — do not infer it from Value == "".

type StaticPart

type StaticPart struct {
	Text string
}

StaticPart is literal text inside an attribute value.

type Text

type Text struct {
	Value string
	Pos   Position
}

Text is literal text between tags/directives. Brace escapes (\{ \}) are already resolved to literal braces.

type Token

type Token struct {
	Type   TokenType
	Value  string
	Quote  byte // delimiter for TokAttrQuoted, else 0
	Raw    bool // attribute token captured while {#raw} has brace grammar disabled
	Line   int
	Col    int
	Offset int
}

Token is one lexical unit. Line/Col are 1-based file coordinates; Offset is the byte offset into the original file.

type TokenType

type TokenType int

TokenType enumerates the lexer's output tokens.

const (
	TokEOF        TokenType = iota
	TokText                 // literal text (brace escapes resolved)
	TokRaw                  // {#raw} body captured verbatim; parser applies parent context
	TokInterp               // { expr }            Value = raw inner
	TokBlockOpen            // {#if ...}/{#for ...} Value = header after '#'
	TokElse                 // {:else}
	TokElseIf               // {:else if cond}     Value = condition (after "else if")
	TokWhen                 // {:when v1, v2, ...}  Value = raw values header after "when"
	TokBlockClose           // {/if}/{/for}        Value = keyword
	TokTagOpen              // <name               Value = tag name; enters tag mode
	TokTagClose             // </name>             Value = tag name
	TokComment              // <!-- ... -->        dropped by the parser
	TokAttrName             // attribute name      Value = name (may start with '@')
	TokEquals               // =
	TokAttrQuoted           // "..."/'...'         Value = raw inner, Quote = delimiter
	TokAttrBrace            // { expr }            Value = inner expr (unquoted value)
	TokAttrBare             // bareword value      Value = word
	TokTagEnd               // >
	TokSelfClose            // />
)

func (TokenType) String

func (t TokenType) String() string

type WhenClause

type WhenClause struct {
	Values []string
	Body   []Node
	Pos    Position
}

WhenClause is one `{:when v1, v2, …}` arm of a Case: its comma-separated top-level Values (OR-matched) and the Body rendered on a match.

Jump to

Keyboard shortcuts

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