expr

package
v0.38.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package expr provides an abstract syntax tree implementation for an expression language.

Status in this fork

Nothing in this repository uses it. It is inherited from upstream's `experimental/` tree, promoted to the top level by Track C (#44), and upstream is in the same position: bufbuild/protocompile's only importer of expr is experimental/internal/exprx, which nothing imports in turn. Wiring it to a consumer is upstream's design question, not this fork's.

It said "shared by various parts of the compiler" until #199, which is how an audit came to read the package as dead code and propose deleting it. It is not dead; it is unfinished, and upstream's.

Two things follow for anyone reading it here. The package is not covered by this repository's test suite, so nothing pins the behaviour described below. And it is NOT the implementation of RFC-001's `expression` parameter type, despite the name: that type is defined as an opaque text payload validated by the configured engine at run time, never parsed by protocompile (see ir.AnnotationParam.IsExpression). The grammar here — `func`, `for ... in`, `break`/`continue`/`return`, and the assignment operators — describes a general-purpose imperative language, which is more than either a validation predicate or a computed default needs.

Node Types

Most types in this package represent AST nodes of some kind. Each such type contains a grammar for the lenient extension of the Protobuf grammar that it represents. The grammar is notated using regular expression syntax, with the following modifications:

  1. Whitespace is ignored.
  2. Literal strings (except in character classes) are represented with Go strings.
  3. Unquoted names refer to other productions.

Productions that represent a type from this package, a token.Kind, or a production used by a different type, are in PascalCase; all other productions are in camelCase and are scoped to that type.

These grammars are provided for illustration only: the complete grammar is ambiguous in the absence of greediness decisions, which, except where otherwise noted, neither affect the parsing of correct Protobuf files, nor are they specified and are subject to change.

Pointer-like Types

Virtually all AST nodes in this library are "pointer-like" types, in that although they are not Go pointers, they do refer to something stored in a Context somewhere. Internally, they contain a pointer to a Context and a pointer to the compressed node representation inside the Context. This is done so that we can avoid spending an extra eight or twelve bytes per node-at-rest, and to minimize GC churn by avoiding pointer cycles in the in-memory representation of the AST.

All pointer-like types have a bool-returning IsZero method, which checks for the zero value. Pointer-like types should generally be passed by value, not by pointer; all of them have value receivers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Block

type Block id.Node[Block, *Context, *rawBlock]

Block := `{` (Expr (`;` | `\n`))* Expr? `}`.

func (Block) AsAny

func (e Block) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (Block) Braces

func (e Block) Braces() token.Token

Braces returns the braces that surround this block.

func (Block) Exprs

func (e Block) Exprs() seq.Inserter[Expr]

Exprs returns an inserter over the expressions in this block.

func (Block) Span

func (e Block) Span() source.Span

Span implements source.Spanner.

type BlockArgs

type BlockArgs struct {
	Braces token.Token
}

BlockArgs is arguments for Nodes.NewBlock.

type Call

type Call id.Node[Call, *Context, *rawCall]

Call is a function call/indexing expression, consisting of an expression followed by bracketed Params.

Grammar

Call := Expr (`(` Params `)` | `[` Params `]` | `{` Params `}`)

func (Call) Args

func (e Call) Args() Params

Args returns the expression's arguments.

func (Call) AsAny

func (e Call) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (Call) Brackets

func (e Call) Brackets() token.Token

Brackets returns the brackets for this call.

func (Call) Callee

func (e Call) Callee() Expr

Callee returns the expression's callee.

func (Call) Span

func (e Call) Span() source.Span

Span implements source.Spanner.

type CallArgs

type CallArgs struct {
	Callee Expr
	Args   Params
}

CallArgs is arguments for Nodes.NewCall.

type Case

type Case id.Node[Case, *Context, *rawCase]

Case is a case block within a Switch.

Grammar

Case := (`case` (Expr `,`)* Expr? | `else`) `:`

func (Case) Alts

func (e Case) Alts() Params

Alts returns the potential alternatives for this case.

func (Case) Block

func (e Case) Block() Block

Block returns the block of expressions for this case.

func (Case) Colon

func (e Case) Colon() token.Token

Colon returns the colon at the end of the alternatives.

func (Case) KeywordToken

func (e Case) KeywordToken() token.Token

KeywordToken returns this switch's "case" or "else" keyword.

func (Case) Kind

func (e Case) Kind() keyword.Keyword

Kind returns which kind of case this is.

func (Case) Span

func (e Case) Span() source.Span

Span implements source.Spanner.

type CaseArgs

type CaseArgs struct {
	Keyword token.Token
	Alts    Params
	Colon   token.Token
	Block   Block
}

CaseArgs is arguments for Nodes.NewCase.

type Context

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

Context is book-keeping for all of the expressions parsed from a particular token.Stream.

This type does not represent an AST node; instead, it is intended to be embedded into the top-level struct for one of the other AST packages in the compiler.

func New

func New(stream *token.Stream) *Context

New creates a fresh expression context for a stream.

func (*Context) FromID

func (c *Context) FromID(id uint64, want any) any

FromID implements id.Context.

func (*Context) Nodes

func (c *Context) Nodes() *Nodes

Nodes returns the node arena for this file, which can be used to allocate new AST nodes.

func (*Context) Stream

func (c *Context) Stream() *token.Stream

Stream returns the underlying token stream.

type Control

type Control id.Node[Control, *Context, *rawControl]

Control is a control flow expression, such as a break or continue, with an optional condition at the end.

Grammar

Switch := (`break` | `continue` | `return`) Params (`if` Expr)?

func (Control) Args

func (e Control) Args() Params

Args returns the arguments for this expression.

func (Control) AsAny

func (e Control) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (Control) Condition

func (e Control) Condition() Expr

Condition returns the condition expression for this expression.

This will be zero if the expression is not conditioned.

func (Control) IfToken

func (e Control) IfToken() token.Token

IfToken returns the token for an `if` after this expression, if it has an associated condition.

func (Control) KeywordToken

func (e Control) KeywordToken() token.Token

KeywordToken returns the token for the keyword for this expression.

func (Control) Kind

func (e Control) Kind() keyword.Keyword

Kind returns what kind of control flow expression this is.

func (Control) Span

func (e Control) Span() source.Span

Span implements source.Spanner.

type ControlArgs

type ControlArgs struct {
	Keyword token.Token
	Args    Params

	If        token.Token
	Condition Expr
}

ControlArgs is arguments for Nodes.NewControl.

type Error

type Error id.Node[Error, *Context, *rawError]

Error is an expression produced due to a parse failure, where a non-zero expression was still needed.

Note that Error is not an [error].

func (Error) AsAny

func (e Error) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (Error) Span

func (e Error) Span() source.Span

Span implements source.Spanner.

type Expr

type Expr id.DynNode[Expr, Kind, *Context]

Expr is any expression type in this package.

Values of this type can be obtained by calling an AsAny method on a expression type, such as Token.AsAny. It can be type-asserted back to any of the concrete expression types using its own As* methods.

This type is used in lieu of a putative Expr interface type to avoid heap allocations in functions that would return one of many different expression types.

Note that the expression and type grammars for the language are the same, so Expr appears in places you might expect to see a "Type" node.

func (Expr) AsBlock

func (e Expr) AsBlock() Block

AsBlock converts an Expr into a Block, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsCall

func (e Expr) AsCall() Call

AsFor converts an Expr into a Call, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsControl

func (e Expr) AsControl() Control

AsControl converts an Expr into a Control, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsError

func (e Expr) AsError() Error

AsError converts an Expr into an Error, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsFor

func (e Expr) AsFor() For

AsFor converts an Expr into a For, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsFunc

func (e Expr) AsFunc() Func

AsFunc converts an Expr into a Func, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsIf

func (e Expr) AsIf() If

AsIf converts an Expr into a If, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsOp

func (e Expr) AsOp() Op

AsOp converts an Expr into a Op, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsRecord

func (e Expr) AsRecord() Record

AsRecord converts an Expr into a Record, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsSwitch

func (e Expr) AsSwitch() Switch

AsSwitch converts an Expr into a Switch, if that is its concrete type.

Otherwise, returns zero.

func (Expr) AsToken

func (e Expr) AsToken() Token

AsToken converts a Any into a ExprLiteral, if that is the type it contains.

Otherwise, returns zero.

func (Expr) Span

func (e Expr) Span() source.Span

Span implements source.Spanner.

type For

type For id.Node[For, *Context, *rawFor]

For is a loop which assigns items out of an iterator to variables in a Params.

Grammar

For := `for` Params `in` Expr Block

func (For) AsAny

func (e For) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (For) Block

func (e For) Block() Block

Block returns this for's block.

func (For) ForToken

func (e For) ForToken() token.Token

Keywords returns this expression's for token.

func (For) InToken

func (e For) InToken() token.Token

Keywords returns this expression's in token.

func (For) Iterator

func (e For) Iterator() Expr

Iterator returns the expression this loop iterates over.

func (For) Span

func (e For) Span() source.Span

Span implements source.Spanner.

func (For) Vars

func (e For) Vars() Params

Vars returns the variables this for assigns to.

type ForArgs

type ForArgs struct {
	For      token.Token
	Vars     Params
	In       token.Token
	Iterator Expr
	Block    Block
}

ForArgs is arguments for Nodes.NewFor.

type Func

type Func id.Node[Func, *Context, *rawFunc]

Func is a function literal or definition. A function definition is simply a function that includes a name after the func keyword.

Grammar

Func := `func` Ident? `(` Params `)` (`->` Expr Block? | Expr)?

func (Func) Arrow

func (e Func) Arrow() token.Token

Arrow returns the arrow that indicates a return type.

func (Func) AsAny

func (e Func) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (Func) Body

func (e Func) Body() Expr

Body returns this function's body expression.

func (Func) FuncToken

func (e Func) FuncToken() token.Token

Keywords returns this expression's func token.

func (Func) Name

func (e Func) Name() token.Token

Name returns the declared function's name (if it is a declaration).

func (Func) Params

func (e Func) Params() Params

Params returns the function's input parameters.

func (Func) Return

func (e Func) Return() Expr

Return returns the type expression for this function's return type.

func (Func) Span

func (e Func) Span() source.Span

Span implements source.Spanner.

type FuncArgs

type FuncArgs struct {
	Func   token.Token
	Name   token.Token
	Params Params
	Arrow  token.Token
	Return Expr
	Body   Expr
}

FuncArgs is arguments for [Nodes.NewFunc].

type If

type If id.Node[If, *Context, *rawIf]

If is a chain of if conditions.

Each If represents one of the blocks in the chain, which may be either an if, an else if, or an else. Only ifs and else ifs have conditions.

Grammar

If := `if` Expr Block (`else` (If | Block))?

func (If) AsAny

func (e If) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (If) Block

func (e If) Block() Block

Block returns this if's block.

func (If) Condition

func (e If) Condition() Expr

Condition returns the condition expression for this if.

This will be zero if it is a final else block.

func (If) Else

func (e If) Else() If

Else returns this if's else block, if it has one.

func (If) ElseToken

func (e If) ElseToken() token.Token

ElseToken returns this expression's else token, if it has one.

func (If) IfToken

func (e If) IfToken() token.Token

IfToken returns this expression's if token, if it has one.

func (If) SetElse

func (e If) SetElse(then If)

SetElse sets this if's else block.

func (If) Span

func (e If) Span() source.Span

Span implements source.Spanner.

type IfArgs

type IfArgs struct {
	Else, If token.Token
	Cond     Expr
	Block    Block
}

IfArgs is arguments for Nodes.NewIf.

type Kind

type Kind int8

Kind is a kind of expression. There is one value of Kind for each expression type in this package.

const (
	KindInvalid Kind = iota
	KindError
	KindToken
	KindRecord
	KindOp
	KindCall
	KindBlock
	KindIf
	KindFor
	KindSwitch
	KindControl
	KindFunc
)

func (Kind) DecodeDynID

func (Kind) DecodeDynID(lo, _ int32) Kind

func (Kind) EncodeDynID

func (k Kind) EncodeDynID(value int32) (int32, int32, bool)

func (Kind) GoString

func (v Kind) GoString() string

GoString implements fmt.GoStringer.

func (Kind) String

func (v Kind) String() string

String implements fmt.Stringer.

type Nodes

type Nodes Context

Nodes provides storage for the various AST node types, and can be used to construct new ones.

func (*Nodes) Context

func (n *Nodes) Context() *Context

File returns the [File] that this Nodes adds nodes to.

func (*Nodes) NewBlock

func (n *Nodes) NewBlock(args BlockArgs) Block

NewBlock constructs a new Block in this context.

func (*Nodes) NewCall

func (n *Nodes) NewCall(args CallArgs) Call

NewCall constructs a new Call in this context.

func (*Nodes) NewCase

func (n *Nodes) NewCase(args CaseArgs) Case

NewCase constructs a new Case in this context.

func (*Nodes) NewControl

func (n *Nodes) NewControl(args ControlArgs) Control

NewCase constructs a new Case in this context.

func (*Nodes) NewError

func (n *Nodes) NewError(span source.Span) Error

NewError constructs a new Error at the given span in this context.

func (*Nodes) NewFor

func (n *Nodes) NewFor(args ForArgs) For

NewFor constructs a new Case in this context.

func (*Nodes) NewIf

func (n *Nodes) NewIf(args IfArgs) If

NewIf constructs a new If in this context.

func (*Nodes) NewOp

func (n *Nodes) NewOp(args OpArgs) Op

NewOp constructs a new Op in this context.

func (*Nodes) NewRecord

func (n *Nodes) NewRecord(args RecordArgs) Record

NewRecord constructs a new Record in this context.

func (*Nodes) NewSwitch

func (n *Nodes) NewSwitch(args SwitchArgs) Switch

NewSwitch constructs a new Switch in this context.

type Op

type Op id.Node[Op, *Context, *rawOp]

Op is an operator expression, consisting of one or two expressions and an operator. This subsumes all of the operator expressions in the grammar, including property, assignment, and range expressions.

Unary do not have a left-hand side.

Grammar

ExprToken := Expr Op Expr

Here, Op is any of the following tokens, ordered from least to greatest precedence (later tokens bind more tightly):

= := += -= *= /= %=
,
or
and
== != < > <= >=
.. ..= to
+ -
* / %
- not (unary)
.

Note that ExprCall has higher precedence than ., so -x.f() will group as -((x.f)()).

func (Op) AsAny

func (e Op) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (Op) IsUnary

func (e Op) IsUnary() bool

IsUnary returns whether this is an unary operation.

func (Op) Left

func (e Op) Left() Expr

Left returns the left-hand side of this expression. Unary operators do not have a left-hand side.

func (Op) Operator

func (e Op) Operator() keyword.Keyword

Operator returns this expression's operator.

func (Op) OperatorToken

func (e Op) OperatorToken() token.Token

OperatorToken returns the token for this expression's operator.

func (Op) Right

func (e Op) Right() Expr

Right returns the right-hand side of this expression.

func (Op) Span

func (e Op) Span() source.Span

Span implements source.Spanner.

type OpArgs

type OpArgs struct {
	Left, Right Expr
	Op          token.Token
}

OpArgs is arguments for Nodes.NewOp.

type Param

type Param struct {
	// The name for this parameter. In a map context, this would be the key;
	// in a function parameter context, this would be the argument name.
	Name Expr

	Colon token.Token
	// The expression for this parameter. In a map context, this would be the value;
	// in a function parameter context, this would be the argument type.
	Expr Expr

	If token.Token
	// A condition for the parameter; not allowed in all productions.
	Cond Expr
}

Param is a parameter in a Params.

func (Param) Span

func (p Param) Span() source.Span

Span implements source.Spanner.

type Params

type Params id.Node[Params, *Context, *rawParams]

Params is a parameter list, which is used for all expression lists in the grammar.

Grammar

Params := (Param `,`)* Param?
Param := Expr (`:` Expr)? (`if` Expr)

func (Params) AppendComma

func (p Params) AppendComma(v Param, comma token.Token)

AppendComma implements [Commas].

func (Params) At

func (p Params) At(n int) Param

At implements seq.Indexer.

func (Params) Brackets

func (p Params) Brackets() token.Token

Brackets returns the token tree for the brackets wrapping the argument list.

May be zero, if the user forgot to include brackets.

func (Params) Comma

func (p Params) Comma(n int) token.Token

Comma implements [Commas].

func (Params) Delete

func (p Params) Delete(n int)

Delete implements seq.Inserter.

func (Params) Insert

func (p Params) Insert(n int, v Param)

Insert implements seq.Inserter.

func (Params) InsertComma

func (p Params) InsertComma(n int, v Param, comma token.Token)

InsertComma implements [Commas].

func (Params) Len

func (p Params) Len() int

Len implements seq.Indexer.

func (Params) SetAt

func (p Params) SetAt(n int, v Param)

SetAt implements seq.Setter.

func (Params) SetBrackets

func (p Params) SetBrackets(brackets token.Token)

SetBrackets sets the token tree for the brackets wrapping the argument list.

func (Params) Span

func (p Params) Span() source.Span

Span implements source.Spanner.

type ParamsArgs

type ParamsArgs struct {
	Brackets token.Token
}

ParamsArgs is arguments for [Nodes.NewParams].

type Record

type Record id.Node[Record, *Context, *rawParams]

Record is a bracketed sequence of expressions, represented as a Params.

Grammar

Record := `(` Params `)` | `[` Params `]` | `{` Params `}`

func (Record) AsAny

func (e Record) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (Record) Brackets

func (e Record) Brackets() token.Token

Brackets returns the brackets for this expression.

func (Record) Entries

func (e Record) Entries() Params

Entries returns the expression's entries.

func (Record) Span

func (e Record) Span() source.Span

Span implements source.Spanner.

type RecordArgs

type RecordArgs struct {
	Entries Params
}

RecordArgs is arguments for Nodes.NewRecord.

type Switch

type Switch id.Node[Switch, *Context, *rawSwitch]

Switch selects one of several blocks to execute based on a number of cases.

Grammar

Switch := `switch` Expr? `{` Case* `}`

func (Switch) Arg

func (e Switch) Arg() Expr

Arg returns the optional argument to the switch.

func (Switch) AsAny

func (e Switch) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (Switch) Braces

func (e Switch) Braces() token.Token

Braces returns the braces for the block within the switch.

func (Switch) Cases

func (e Switch) Cases() seq.Inserter[Case]

Cases returns the cases contained within the switch.

func (Switch) Span

func (e Switch) Span() source.Span

Span implements source.Spanner.

func (Switch) SwitchToken

func (e Switch) SwitchToken() token.Token

SwitchToken returns this expression's switch token.

type SwitchArgs

type SwitchArgs struct {
	Switch token.Token
	Arg    Expr
	Braces token.Token
}

SwitchArgs is arguments for Nodes.NewSwitch.

type Token

type Token struct {
	ExprContext *Context
	// The token backing this expression. Must be [token.String], [token.Number],
	// or [token.Ident].
	token.Token
}

Token is an expression corresponding to a single token: a string, a number, or an identifier.

Grammar

Token := token.Number | token.String | token.Ident

func (Token) AsAny

func (e Token) AsAny() Expr

AsAny type-erases this type value.

See Expr for more information.

func (Token) Context

func (e Token) Context() *Context

Context returns this token's context.

This returns a Context rather than a token.Stream, which would otherwise be returned because Token embeds token.Token.

Jump to

Keyboard shortcuts

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