ast

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2024 License: Apache-2.0, BSD-3-Clause Imports: 6 Imported by: 27

Documentation

Overview

Package ast declares data structures useful for parsed and checked abstract syntax trees

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConstantToVal

func ConstantToVal(c *exprpb.Constant) (ref.Val, error)

ConstantToVal converts a protobuf Constant to a CEL-native ref.Val.

func EntryExprToProto added in v0.17.2

func EntryExprToProto(e EntryExpr) (*exprpb.Expr_CreateStruct_Entry, error)

EntryExprToProto converts an ast.EntryExpr to a protobuf CreateStruct entry

func ExprToProto added in v0.17.2

func ExprToProto(e Expr) (*exprpb.Expr, error)

ExprToProto serializes an ast.Expr value to a protobuf Expr representation.

func MaxID added in v0.18.0

func MaxID(a *AST) int64

MaxID returns the upper-bound, non-inclusive, of ids present within the AST's Expr value.

func PostOrderVisit added in v0.18.0

func PostOrderVisit(expr Expr, visitor Visitor)

PostOrderVisit walks the expression graph and calls the visitor in post-order (bottom-up).

func PreOrderVisit added in v0.18.0

func PreOrderVisit(expr Expr, visitor Visitor)

PreOrderVisit walks the expression graph and calls the visitor in pre-order (top-down).

func ReferenceInfoToProto added in v0.17.2

func ReferenceInfoToProto(info *ReferenceInfo) (*exprpb.Reference, error)

ReferenceInfoToProto converts a ReferenceInfo instance to a protobuf Reference suitable for serialization.

func SourceInfoToProto added in v0.17.2

func SourceInfoToProto(info *SourceInfo) (*exprpb.SourceInfo, error)

SourceInfoToProto serializes an ast.SourceInfo value to a protobuf SourceInfo object.

func ToProto added in v0.17.2

func ToProto(ast *AST) (*exprpb.CheckedExpr, error)

ToProto converts an AST to a CheckedExpr protobouf.

func ValToConstant

func ValToConstant(v ref.Val) (*exprpb.Constant, error)

ValToConstant converts a CEL-native ref.Val to a protobuf Constant.

Only simple scalar types are supported by this method.

Types

type AST added in v0.17.2

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

AST contains a protobuf expression and source info along with CEL-native type and reference information.

func Copy added in v0.17.2

func Copy(a *AST) *AST

Copy creates a deep copy of the Expr and SourceInfo values in the input AST.

Copies of the Expr value are generated using an internal default ExprFactory.

func NewAST added in v0.17.2

func NewAST(e Expr, sourceInfo *SourceInfo) *AST

NewAST creates a base AST instance with an ast.Expr and ast.SourceInfo value.

func NewCheckedAST added in v0.17.2

func NewCheckedAST(parsed *AST, typeMap map[int64]*types.Type, refMap map[int64]*ReferenceInfo) *AST

NewCheckedAST wraps an parsed AST and augments it with type and reference metadata.

func ToAST added in v0.17.2

func ToAST(checked *exprpb.CheckedExpr) (*AST, error)

ToAST converts a CheckedExpr protobuf to an AST instance.

func (*AST) Expr added in v0.17.2

func (a *AST) Expr() Expr

Expr returns the root ast.Expr value in the AST.

func (*AST) GetOverloadIDs added in v0.17.2

func (a *AST) GetOverloadIDs(id int64) []string

GetOverloadIDs returns the set of overload function names for a given expression id.

If the expression id is not a function call, or the AST is not type-checked, the result will be empty.

func (*AST) GetType added in v0.17.2

func (a *AST) GetType(id int64) *types.Type

GetType returns the type for the expression at the given id, if one exists, else types.DynType.

func (*AST) IsChecked added in v0.17.2

func (a *AST) IsChecked() bool

IsChecked returns whether the AST is type-checked.

func (*AST) ReferenceMap added in v0.17.2

func (a *AST) ReferenceMap() map[int64]*ReferenceInfo

ReferenceMap returns the map of expression id to identifier, constant, and function references.

func (*AST) SetReference added in v0.17.2

func (a *AST) SetReference(id int64, r *ReferenceInfo)

SetReference adds a reference to the checked AST type map.

func (*AST) SetType added in v0.17.2

func (a *AST) SetType(id int64, t *types.Type)

SetType sets the type of the expression node at the given id.

func (*AST) SourceInfo added in v0.17.2

func (a *AST) SourceInfo() *SourceInfo

SourceInfo returns the source metadata associated with the parse / type-check passes.

func (*AST) TypeMap added in v0.17.2

func (a *AST) TypeMap() map[int64]*types.Type

TypeMap returns the map of expression ids to type-checked types.

If the AST is not type-checked, the map will be empty.

type CallExpr added in v0.17.2

type CallExpr interface {
	// FunctionName returns the name of the function.
	FunctionName() string

	// IsMemberFunction returns whether the call has a non-nil target indicating it is a member function
	IsMemberFunction() bool

	// Target returns the target of the expression if one is present.
	Target() Expr

	// Args returns the list of call arguments, excluding the target.
	Args() []Expr
	// contains filtered or unexported methods
}

CallExpr defines an interface for inspecting a function call and its arguments.

type ComprehensionExpr added in v0.17.2

type ComprehensionExpr interface {
	// IterRange returns the iteration range expression.
	IterRange() Expr

	// IterVar returns the iteration variable name.
	IterVar() string

	// AccuVar returns the accumulation variable name.
	AccuVar() string

	// AccuInit returns the accumulation variable initialization expression.
	AccuInit() Expr

	// LoopCondition returns the loop condition expression.
	LoopCondition() Expr

	// LoopStep returns the loop step expression.
	LoopStep() Expr

	// Result returns the comprehension result expression.
	Result() Expr
	// contains filtered or unexported methods
}

ComprehensionExpr defines an interface for inspecting a comprehension expression.

type EntryExpr added in v0.17.2

type EntryExpr interface {
	// ID of the entry as it appears in the AST.
	ID() int64

	// Kind of the entry expression node. See EntryExprKind for valid enum values.
	Kind() EntryExprKind

	// AsMapEntry casts the EntryExpr to a MapEntry.
	//
	// The Kind() must be equal to MapEntryKind for the conversion to be well-defined.
	AsMapEntry() MapEntry

	// AsStructField casts the EntryExpr to a StructField
	//
	// The Kind() must be equal to StructFieldKind for the conversion to be well-defined.
	AsStructField() StructField

	// RenumberIDs performs an in-place update of the expression and all of its descendents numeric ids.
	RenumberIDs(IDGenerator)
	// contains filtered or unexported methods
}

EntryExpr represents the base entry expression in a CEL map or struct literal.

func ProtoToEntryExpr added in v0.17.2

func ProtoToEntryExpr(e *exprpb.Expr_CreateStruct_Entry) (EntryExpr, error)

ProtoToEntryExpr converts a protobuf struct/map entry to an ast.EntryExpr

type EntryExprKind added in v0.17.2

type EntryExprKind int

EntryExprKind represents the possible EntryExpr kinds.

const (
	// UnspecifiedEntryExprKind indicates that the entry expr is not set.
	UnspecifiedEntryExprKind EntryExprKind = iota

	// MapEntryKind indicates that the entry is a MapEntry type with key and value expressions.
	MapEntryKind

	// StructFieldKind indicates that the entry is a StructField with a field name and initializer
	// expression.
	StructFieldKind
)

type Expr added in v0.17.2

type Expr interface {
	// ID of the expression as it appears in the AST
	ID() int64

	// Kind of the expression node. See ExprKind for the valid enum values.
	Kind() ExprKind

	// AsCall adapts the expr into a CallExpr
	//
	// The Kind() must be equal to a CallKind for the conversion to be well-defined.
	AsCall() CallExpr

	// AsComprehension adapts the expr into a ComprehensionExpr.
	//
	// The Kind() must be equal to a ComprehensionKind for the conversion to be well-defined.
	AsComprehension() ComprehensionExpr

	// AsIdent adapts the expr into an identifier string.
	//
	// The Kind() must be equal to an IdentKind for the conversion to be well-defined.
	AsIdent() string

	// AsLiteral adapts the expr into a constant ref.Val.
	//
	// The Kind() must be equal to a LiteralKind for the conversion to be well-defined.
	AsLiteral() ref.Val

	// AsList adapts the expr into a ListExpr.
	//
	// The Kind() must be equal to a ListKind for the conversion to be well-defined.
	AsList() ListExpr

	// AsMap adapts the expr into a MapExpr.
	//
	// The Kind() must be equal to a MapKind for the conversion to be well-defined.
	AsMap() MapExpr

	// AsSelect adapts the expr into a SelectExpr.
	//
	// The Kind() must be equal to a SelectKind for the conversion to be well-defined.
	AsSelect() SelectExpr

	// AsStruct adapts the expr into a StructExpr.
	//
	// The Kind() must be equal to a StructKind for the conversion to be well-defined.
	AsStruct() StructExpr

	// RenumberIDs performs an in-place update of the expression and all of its descendents numeric ids.
	RenumberIDs(IDGenerator)

	// SetKindCase replaces the contents of the current expression with the contents of the other.
	//
	// The SetKindCase takes ownership of any expression instances references within the input Expr.
	// A shallow copy is made of the Expr value itself, but not a deep one.
	//
	// This method should only be used during AST rewrites using temporary Expr values.
	SetKindCase(Expr)
	// contains filtered or unexported methods
}

Expr represents the base expression node in a CEL abstract syntax tree.

Depending on the `Kind()` value, the Expr may be converted to a concrete expression types as indicated by the `As<Kind>` methods.

func ProtoToExpr added in v0.17.2

func ProtoToExpr(e *exprpb.Expr) (Expr, error)

ProtoToExpr converts a protobuf Expr value to an ast.Expr value.

type ExprFactory added in v0.17.2

type ExprFactory interface {
	// CopyExpr creates a deep copy of the input Expr value.
	CopyExpr(Expr) Expr

	// CopyEntryExpr creates a deep copy of the input EntryExpr value.
	CopyEntryExpr(EntryExpr) EntryExpr

	// NewCall creates an Expr value representing a global function call.
	NewCall(id int64, function string, args ...Expr) Expr

	// NewComprehension creates an Expr value representing a comprehension over a value range.
	NewComprehension(id int64, iterRange Expr, iterVar, accuVar string, accuInit, loopCondition, loopStep, result Expr) Expr

	// NewMemberCall creates an Expr value representing a member function call.
	NewMemberCall(id int64, function string, receiver Expr, args ...Expr) Expr

	// NewIdent creates an Expr value representing an identifier.
	NewIdent(id int64, name string) Expr

	// NewAccuIdent creates an Expr value representing an accumulator identifier within a
	//comprehension.
	NewAccuIdent(id int64) Expr

	// NewLiteral creates an Expr value representing a literal value, such as a string or integer.
	NewLiteral(id int64, value ref.Val) Expr

	// NewList creates an Expr value representing a list literal expression with optional indices.
	//
	// Optional indicies will typically be empty unless the CEL optional types are enabled.
	NewList(id int64, elems []Expr, optIndices []int32) Expr

	// NewMap creates an Expr value representing a map literal expression
	NewMap(id int64, entries []EntryExpr) Expr

	// NewMapEntry creates a MapEntry with a given key, value, and a flag indicating whether
	// the key is optionally set.
	NewMapEntry(id int64, key, value Expr, isOptional bool) EntryExpr

	// NewPresenceTest creates an Expr representing a field presence test on an operand expression.
	NewPresenceTest(id int64, operand Expr, field string) Expr

	// NewSelect creates an Expr representing a field selection on an operand expression.
	NewSelect(id int64, operand Expr, field string) Expr

	// NewStruct creates an Expr value representing a struct literal with a given type name and a
	// set of field initializers.
	NewStruct(id int64, typeName string, fields []EntryExpr) Expr

	// NewStructField creates a StructField with a given field name, value, and a flag indicating
	// whether the field is optionally set.
	NewStructField(id int64, field string, value Expr, isOptional bool) EntryExpr

	// NewUnspecifiedExpr creates an empty expression node.
	NewUnspecifiedExpr(id int64) Expr
	// contains filtered or unexported methods
}

ExprFactory interfaces defines a set of methods necessary for building native expression values.

func NewExprFactory added in v0.17.2

func NewExprFactory() ExprFactory

NewExprFactory creates an ExprFactory instance.

type ExprKind

type ExprKind int

ExprKind represents the expression node kind.

const (
	// UnspecifiedExprKind represents an unset expression with no specified properties.
	UnspecifiedExprKind ExprKind = iota

	// CallKind represents a function call.
	CallKind

	// ComprehensionKind represents a comprehension expression generated by a macro.
	ComprehensionKind

	// IdentKind represents a simple variable, constant, or type identifier.
	IdentKind

	// ListKind represents a list literal expression.
	ListKind

	// LiteralKind represents a primitive scalar literal.
	LiteralKind

	// MapKind represents a map literal expression.
	MapKind

	// SelectKind represents a field selection expression.
	SelectKind

	// StructKind represents a struct literal expression.
	StructKind
)

type ExprMatcher

type ExprMatcher func(NavigableExpr) bool

ExprMatcher takes a NavigableExpr in and indicates whether the value is a match.

This function type should be use with the `Match` and `MatchList` calls.

func AllMatcher

func AllMatcher() ExprMatcher

AllMatcher returns true for all descendants of a NavigableExpr, effectively flattening them into a list.

Such a result would work well with subsequent MatchList calls.

func ConstantValueMatcher

func ConstantValueMatcher() ExprMatcher

ConstantValueMatcher returns an ExprMatcher which will return true if the input NavigableExpr is comprised of all constant values, such as a simple literal or even list and map literal.

func FunctionMatcher

func FunctionMatcher(funcName string) ExprMatcher

FunctionMatcher returns an ExprMatcher which will match NavigableExpr nodes of CallKind type whose function name is equal to `funcName`.

func KindMatcher

func KindMatcher(kind ExprKind) ExprMatcher

KindMatcher returns an ExprMatcher which will return true if the input NavigableExpr.Kind() matches the specified `kind`.

type IDGenerator added in v0.17.2

type IDGenerator func(originalID int64) int64

IDGenerator produces unique ids suitable for tagging expression nodes

type ListExpr added in v0.17.2

type ListExpr interface {
	// Elements returns the list elements as navigable expressions.
	Elements() []Expr

	// OptionalIndicies returns the list of optional indices in the list literal.
	OptionalIndices() []int32

	// IsOptional indicates whether the given element index is optional.
	IsOptional(int32) bool

	// Size returns the number of elements in the list.
	Size() int
	// contains filtered or unexported methods
}

ListExpr defines an interface for inspecting a list literal expression.

type MapEntry added in v0.17.2

type MapEntry interface {
	// Key returns the map entry key expression.
	Key() Expr

	// Value returns the map entry value expression.
	Value() Expr

	// IsOptional returns whether the entry is optional.
	IsOptional() bool
	// contains filtered or unexported methods
}

MapEntry defines an interface for inspecting a map entry.

type MapExpr added in v0.17.2

type MapExpr interface {
	// Entries returns the map key value pairs as EntryExpr values.
	Entries() []EntryExpr

	// Size returns the number of entries in the map.
	Size() int
	// contains filtered or unexported methods
}

MapExpr defines an interface for inspecting a map expression.

type NavigableExpr interface {
	Expr

	// Type of the expression.
	//
	// If the expression is type-checked, the type check metadata is returned. If the expression
	// has not been type-checked, the types.DynType value is returned.
	Type() *types.Type

	// Parent returns the parent expression node, if one exists.
	Parent() (NavigableExpr, bool)

	// Children returns a list of child expression nodes.
	Children() []NavigableExpr

	// Depth indicates the depth in the expression tree.
	//
	// The root expression has depth 0.
	Depth() int
}

NavigableExpr represents the base navigable expression value with methods to inspect the parent and child expressions.

func MatchDescendants

func MatchDescendants(expr NavigableExpr, matcher ExprMatcher) []NavigableExpr

MatchDescendants takes a NavigableExpr and ExprMatcher and produces a list of NavigableExpr values matching the input criteria in post-order (bottom up).

func MatchSubset

func MatchSubset(exprs []NavigableExpr, matcher ExprMatcher) []NavigableExpr

MatchSubset applies an ExprMatcher to a list of NavigableExpr values and their descendants, producing a subset of NavigableExpr values which match.

func NavigateAST(ast *AST) NavigableExpr

NavigateAST converts an AST to a NavigableExpr

func NavigateExpr(ast *AST, expr Expr) NavigableExpr

NavigateExpr creates a NavigableExpr whose type information is backed by the input AST.

If the expression is already a NavigableExpr, the parent and depth information will be propagated on the new NavigableExpr value; otherwise, the expr value will be treated as though it is the root of the expression graph with a depth of 0.

type OffsetRange added in v0.17.2

type OffsetRange struct {
	Start int32
	Stop  int32
}

OffsetRange captures the start and stop positions of a section of text in the input expression.

type ReferenceInfo

type ReferenceInfo struct {
	Name        string
	OverloadIDs []string
	Value       ref.Val
}

ReferenceInfo contains a CEL native representation of an identifier reference which may refer to either a qualified identifier name, a set of overload ids, or a constant value from an enum.

func NewFunctionReference

func NewFunctionReference(overloads ...string) *ReferenceInfo

NewFunctionReference creates a ReferenceInfo instance for a set of function overloads.

func NewIdentReference

func NewIdentReference(name string, value ref.Val) *ReferenceInfo

NewIdentReference creates a ReferenceInfo instance for an identifier with an optional constant value.

func ProtoToReferenceInfo added in v0.17.2

func ProtoToReferenceInfo(ref *exprpb.Reference) (*ReferenceInfo, error)

ProtoToReferenceInfo converts a protobuf Reference into a CEL-native ReferenceInfo instance.

func (*ReferenceInfo) AddOverload

func (r *ReferenceInfo) AddOverload(overloadID string)

AddOverload appends a function overload ID to the ReferenceInfo.

func (*ReferenceInfo) Equals

func (r *ReferenceInfo) Equals(other *ReferenceInfo) bool

Equals returns whether two references are identical to each other.

type SelectExpr added in v0.17.2

type SelectExpr interface {
	// Operand returns the selection operand expression.
	Operand() Expr

	// FieldName returns the field name being selected from the operand.
	FieldName() string

	// IsTestOnly indicates whether the select expression is a presence test generated by a macro.
	IsTestOnly() bool
	// contains filtered or unexported methods
}

SelectExpr defines an interface for inspecting a select expression.

type SourceInfo added in v0.17.2

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

SourceInfo records basic information about the expression as a textual input and as a parsed expression value.

func CopySourceInfo added in v0.17.2

func CopySourceInfo(info *SourceInfo) *SourceInfo

CopySourceInfo creates a deep copy of the MacroCalls within the input SourceInfo.

Copies of macro Expr values are generated using an internal default ExprFactory.

func NewSourceInfo added in v0.17.2

func NewSourceInfo(src common.Source) *SourceInfo

NewSourceInfo creates a simple SourceInfo object from an input common.Source value.

func ProtoToSourceInfo added in v0.17.2

func ProtoToSourceInfo(info *exprpb.SourceInfo) (*SourceInfo, error)

ProtoToSourceInfo deserializes the protobuf into a native SourceInfo value.

func (*SourceInfo) ClearMacroCall added in v0.18.0

func (s *SourceInfo) ClearMacroCall(id int64)

ClearMacroCall removes the macro call at the given expression id.

func (*SourceInfo) ClearOffsetRange added in v0.21.0

func (s *SourceInfo) ClearOffsetRange(id int64)

ClearOffsetRange removes the OffsetRange for the given expression id.

func (*SourceInfo) ComputeOffset added in v0.17.2

func (s *SourceInfo) ComputeOffset(line, col int32) int32

ComputeOffset calculates the 0-based character offset from a 1-based line and 0-based column.

func (*SourceInfo) Description added in v0.17.2

func (s *SourceInfo) Description() string

Description provides information about where the expression came from.

func (*SourceInfo) GetLocationByOffset added in v0.21.0

func (s *SourceInfo) GetLocationByOffset(offset int32) common.Location

GetLocationByOffset returns the line and column information for a given character offset.

func (*SourceInfo) GetMacroCall added in v0.17.2

func (s *SourceInfo) GetMacroCall(id int64) (Expr, bool)

GetMacroCall returns the original ast.Expr value for the given expression if it was generated via a macro replacement.

Note, parsing options must be enabled to track macro calls before this method will return a value.

func (*SourceInfo) GetOffsetRange added in v0.17.2

func (s *SourceInfo) GetOffsetRange(id int64) (OffsetRange, bool)

GetOffsetRange retrieves an OffsetRange for the given expression id if one exists.

func (*SourceInfo) GetStartLocation added in v0.17.2

func (s *SourceInfo) GetStartLocation(id int64) common.Location

GetStartLocation calculates the human-readable 1-based line and 0-based column of the first character of the expression node at the id.

func (*SourceInfo) GetStopLocation added in v0.17.2

func (s *SourceInfo) GetStopLocation(id int64) common.Location

GetStopLocation calculates the human-readable 1-based line and 0-based column of the last character for the expression node at the given id.

If the SourceInfo was generated from a serialized protobuf representation, the stop location will be identical to the start location for the expression.

func (*SourceInfo) LineOffsets added in v0.17.2

func (s *SourceInfo) LineOffsets() []int32

LineOffsets returns a list of the 0-based character offsets in the input text where newlines appear.

func (*SourceInfo) MacroCalls added in v0.17.2

func (s *SourceInfo) MacroCalls() map[int64]Expr

MacroCalls returns a map of expression id to ast.Expr value where the id represents the expression node where the macro was inserted into the AST, and the ast.Expr value represents the original call signature which was replaced.

func (*SourceInfo) OffsetRanges added in v0.17.2

func (s *SourceInfo) OffsetRanges() map[int64]OffsetRange

OffsetRanges returns a map of expression id to OffsetRange values where the range indicates either: the start and end position in the input stream where the expression occurs, or the start position only. If the range only captures start position, the stop position of the range will be equal to the start.

func (*SourceInfo) SetMacroCall added in v0.17.2

func (s *SourceInfo) SetMacroCall(id int64, e Expr)

SetMacroCall records a macro call at a specific location.

func (*SourceInfo) SetOffsetRange added in v0.17.2

func (s *SourceInfo) SetOffsetRange(id int64, o OffsetRange)

SetOffsetRange sets the OffsetRange for the given expression id.

func (*SourceInfo) SyntaxVersion added in v0.17.2

func (s *SourceInfo) SyntaxVersion() string

SyntaxVersion returns the syntax version associated with the text expression.

type StructExpr added in v0.17.2

type StructExpr interface {
	// TypeName returns the struct type name.
	TypeName() string

	// Fields returns the set of field initializers in the struct expression as EntryExpr values.
	Fields() []EntryExpr
	// contains filtered or unexported methods
}

StructExpr defines an interfaces for inspecting a struct and its field initializers.

type StructField added in v0.17.2

type StructField interface {
	// Name returns the name of the field.
	Name() string

	// Value returns the field initialization expression.
	Value() Expr

	// IsOptional returns whether the field is optional.
	IsOptional() bool
	// contains filtered or unexported methods
}

StructField defines an interface for inspecting a struct field initialization.

type Visitor added in v0.18.0

type Visitor interface {
	// VisitExpr visits the input expression.
	VisitExpr(Expr)

	// VisitEntryExpr visits the input entry expression, i.e. a struct field or map entry.
	VisitEntryExpr(EntryExpr)
}

Visitor defines an object for visiting Expr and EntryExpr nodes within an expression graph.

func NewExprVisitor added in v0.18.0

func NewExprVisitor(v func(Expr)) Visitor

NewExprVisitor creates a visitor which only visits expression nodes.

Jump to

Keyboard shortcuts

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