Documentation
¶
Overview ¶
Package classad provides a public API for working with HTCondor ClassAds. It mimics the C++ ClassAd library API from HTCondor.
Concurrency ¶
A *ClassAd may be read by any number of goroutines at once. Reading covers every method that does not change the ad: serialization (String, MarshalOld, MarshalJSON and their WithPrivate forms, json.Marshal), Equal, Lookup, Size, GetAttributes, AST, Redacted, Flatten, ExternalRefs/InternalRefs, and evaluation (EvaluateAttr*, EvaluateExpr*, Expr.Eval, Expr.EvalWithContext, EvaluateExprWithTarget, EvaluateExprAgainst). Reads do not modify the ad, so they need no locking and see consistent results.
Writes need exclusive access: while one runs, no other goroutine may read or write the same ad. The writes are Insert and the methods built on it (InsertAttr*, InsertExpr, InsertListElement, InsertAttrList, Set), Delete, Clear, UnmarshalJSON, SetParent and SetTarget. NewMatchClassAd, ReplaceLeftAd and ReplaceRightAd call SetTarget on the ads they pair, so they are writes to both; to evaluate against a target that other goroutines share, use EvaluateExprAgainst, which binds MY and TARGET for one evaluation without changing either ad. An Evaluator is not safe for concurrent use (create one per goroutine); the ads it evaluates are only read.
A Value is immutable and may be shared. A ClassAd obtained from a Value (a nested record) is a read-only view of the ad it came from; writing it detaches it onto a private copy and never changes that ad.
Package classad provides ClassAd matching functionality.
Package classad provides ClassAd matching functionality.
Example (UserDefinedFunction) ¶
Example_userDefinedFunction registers a scalar function and calls it from an ordinary expression. A registered name is a function like any built-in: the parser does not know it is user-defined, name lookup folds case, and the compiler lowers a call to it natively rather than delegating the expression to the tree-walking evaluator.
The three calls below are the three answers a UDF has to be able to give, and the reason the signature returns a Value rather than (Value, error): UNDEFINED and ERROR are values in this language, and which one a missing argument deserves is the function's decision, not the caller's.
package main
import (
"fmt"
"github.com/PelicanPlatform/classad/classad"
)
func main() {
// pctUsed(used, total) -- what fraction of a resource is in use, as a percentage.
err := classad.RegisterFunction("pctUsed", 2, 2, func(args []classad.Value) classad.Value {
// Undefined in, undefined out. An attribute the ad does not carry is not a
// mistake, and a Requirements expression that treated it as one would reject
// the machine instead of ignoring the term.
if args[0].IsUndefined() || args[1].IsUndefined() {
return classad.NewUndefinedValue()
}
used, uerr := args[0].NumberValue()
total, terr := args[1].NumberValue()
if uerr != nil || terr != nil || total == 0 {
// A string where a number belongs, or a division that has no answer.
// Report it by RETURNING ERROR; do not panic. A panic here is
// contained, but containment is a backstop and not an interface.
return classad.NewErrorValue()
}
return classad.NewRealValue(used / total * 100)
})
if err != nil {
panic(err)
}
ad, err := classad.Parse(`[ Used = 3; Total = 8; Label = "eight" ]`)
if err != nil {
panic(err)
}
for _, src := range []string{
`pctUsed(Used, Total)`, // both numbers
`PCTUSED(Used, Total)`, // names fold, as every function name does
`pctUsed(Used, Absent)`, // an attribute the ad does not carry
`pctUsed(Used, Label)`, // a string where a number belongs
} {
expr, err := classad.ParseExpr(src)
if err != nil {
panic(err)
}
fmt.Printf("%-24s %s\n", src, expr.Eval(ad).String())
}
// A UDF stays eligible for the compiled and columnar paths because it promised purity by
// its signature: it is handed values, so it cannot read an attribute the compiler did not
// know the expression would read.
fmt.Println("compilable:", classad.StrictFunction("pctUsed", 2))
}
Output: pctUsed(Used, Total) 37.5 PCTUSED(Used, Total) 37.5 pctUsed(Used, Absent) undefined pctUsed(Used, Label) error compilable: true
Index ¶
- Variables
- func All(r io.Reader) iter.Seq[*ClassAd]
- func AllOld(r io.Reader) iter.Seq[*ClassAd]
- func AllOldWithError(r io.Reader, errPtr *error) iter.Seq[*ClassAd]
- func AllOldWithIndex(r io.Reader) iter.Seq2[int, *ClassAd]
- func AllWithError(r io.Reader, errPtr *error) iter.Seq[*ClassAd]
- func AllWithIndex(r io.Reader) iter.Seq2[int, *ClassAd]
- func BuiltinFunctionName(name string) bool
- func CompareStringsFold(a, b string) int
- func FoldConstants(e ast.Expr) ast.Expr
- func FoldConstantsAt(e ast.Expr, now int64) ast.Expr
- func GetAs[T any](c *ClassAd, name string) (T, bool)
- func GetOr[T any](c *ClassAd, name string, defaultValue T) T
- func InsertAttrList[T int64 | float64 | string | bool | *ClassAd | *Expr](c *ClassAd, name string, values []T)
- func IsCurrentTimeName(name string) bool
- func IsCurrentTimeRef(ref *ast.AttributeReference) bool
- func IsPrivateAttribute(name string) bool
- func IsPrivateAttributeV1(name string) bool
- func IsPrivateAttributeV2(name string) bool
- func KnownFunctionName(name string) bool
- func Marshal(v interface{}) (string, error)
- func MarshalClassAd(v interface{}) (string, error)
- func Quote(s string) string
- func RecoverCyclic(result *Value)
- func RegisterFunction(name string, minArgs, maxArgs int, fn Func) error
- func RegisteredFunctions() []string
- func SplitStringList(list, delimiter string) []string
- func StrictFunction(name string, argc int) bool
- func StringListArg(v Value) (string, bool)
- func Unmarshal(data string, v interface{}) error
- func UnmarshalClassAd(data string, v interface{}) error
- func Unquote(s string) (string, error)
- type ClassAd
- func (c *ClassAd) AST() *ast.ClassAd
- func (c *ClassAd) Clear()
- func (c *ClassAd) Delete(name string) bool
- func (c *ClassAd) Equal(other *ClassAd) bool
- func (c *ClassAd) EvaluateAttr(name string) (result Value)
- func (c *ClassAd) EvaluateAttrBool(name string) (bool, bool)
- func (c *ClassAd) EvaluateAttrInt(name string) (int64, bool)
- func (c *ClassAd) EvaluateAttrNumber(name string) (float64, bool)
- func (c *ClassAd) EvaluateAttrReal(name string) (float64, bool)
- func (c *ClassAd) EvaluateAttrString(name string) (string, bool)
- func (c *ClassAd) EvaluateExpr(expr ast.Expr) (result Value)
- func (c *ClassAd) EvaluateExprAgainst(expr ast.Expr, target *ClassAd) (result Value)
- func (c *ClassAd) EvaluateExprString(exprStr string) (Value, error)
- func (c *ClassAd) EvaluateExprWithTarget(expr *Expr, target *ClassAd) Value
- func (c *ClassAd) ExternalRefs(expr *Expr) []string
- func (c *ClassAd) Flatten(expr *Expr) *Expr
- func (c *ClassAd) GetAttributes() []string
- func (c *ClassAd) GetParent() *ClassAd
- func (c *ClassAd) GetTarget() *ClassAd
- func (c *ClassAd) Insert(name string, expr ast.Expr)
- func (c *ClassAd) InsertAttr(name string, value int64)
- func (c *ClassAd) InsertAttrBool(name string, value bool)
- func (c *ClassAd) InsertAttrClassAd(name string, value *ClassAd)
- func (c *ClassAd) InsertAttrFloat(name string, value float64)
- func (c *ClassAd) InsertAttrString(name, value string)
- func (c *ClassAd) InsertExpr(name string, expr *Expr)
- func (c *ClassAd) InsertListElement(name string, element *Expr)
- func (c *ClassAd) InternalRefs(expr *Expr) []string
- func (c *ClassAd) Lookup(name string) (*Expr, bool)
- func (c *ClassAd) MarshalJSON() ([]byte, error)
- func (c *ClassAd) MarshalJSONWithPrivate() ([]byte, error)
- func (c *ClassAd) MarshalOld() string
- func (c *ClassAd) MarshalOldWithPrivate() string
- func (c *ClassAd) Redacted() *ClassAd
- func (c *ClassAd) Set(name string, value any) error
- func (c *ClassAd) SetParent(parent *ClassAd)
- func (c *ClassAd) SetTarget(target *ClassAd)
- func (c *ClassAd) Size() int
- func (c *ClassAd) String() string
- func (c *ClassAd) StringWithPrivate() string
- func (c *ClassAd) UnmarshalJSON(data []byte) error
- type CondState
- type Evaluator
- func (e *Evaluator) ApplyBinaryOp(op string, left, right Value) Value
- func (e *Evaluator) ApplySubscript(container, index Value) Value
- func (e *Evaluator) ApplyUnaryOp(op string, operand Value) Value
- func (e *Evaluator) Evaluate(expr ast.Expr) Value
- func (e *Evaluator) PinCurrentTime(now int64)
- func (e *Evaluator) ResolveAlias(alias int, name string) (Value, bool)
- func (e *Evaluator) ResolveRef(name string, scope ast.AttributeScope) Value
- func (e *Evaluator) ResolveRefNode(ref *ast.AttributeReference) Value
- func (e *Evaluator) SetAliasResolver(fn func(alias int, name string) Value)
- func (e *Evaluator) SetPartialResolver(fn func(name string, scope ast.AttributeScope) (Value, bool))
- func (e *Evaluator) SetResolver(fn func(name string, scope ast.AttributeScope) Value)
- func (e *Evaluator) SetScope(ad *ClassAd)
- func (e *Evaluator) ShortCircuit(op string, left Value) (result Value, done bool)
- type Expr
- func (e *Expr) AST() ast.Expr
- func (e *Expr) Equal(other *Expr) bool
- func (e *Expr) Eval(scope *ClassAd) (result Value)
- func (e *Expr) EvalWithContext(scope, target *ClassAd) (result Value)
- func (e *Expr) FoldConstants() *Expr
- func (e *Expr) String() string
- func (e *Expr) Unparse() string
- func (e *Expr) UnparseOld() string
- type Func
- type Marshaler
- type MatchClassAd
- func (m *MatchClassAd) EvaluateAttrLeft(name string) Value
- func (m *MatchClassAd) EvaluateAttrRight(name string) Value
- func (m *MatchClassAd) EvaluateExprLeft(expr ast.Expr) Value
- func (m *MatchClassAd) EvaluateExprRight(expr ast.Expr) Value
- func (m *MatchClassAd) EvaluateRankLeft() (float64, bool)
- func (m *MatchClassAd) EvaluateRankRight() (float64, bool)
- func (m *MatchClassAd) GetLeftAd() *ClassAd
- func (m *MatchClassAd) GetRightAd() *ClassAd
- func (m *MatchClassAd) Match() bool
- func (m *MatchClassAd) ReplaceLeftAd(left *ClassAd)
- func (m *MatchClassAd) ReplaceRightAd(right *ClassAd)
- func (m *MatchClassAd) Symmetry(leftReqAttr, rightReqAttr string) bool
- type Reader
- type Unmarshaler
- type Value
- func ApplyFunction(e *Evaluator, name string, args []Value) Value
- func Avg(values []Value) Value
- func Max(values []Value) Value
- func Min(values []Value) Value
- func NewBoolValue(b bool) Value
- func NewClassAdValue(ad *ClassAd) Value
- func NewErrorValue() Value
- func NewIntValue(i int64) Value
- func NewListValue(list []Value) Value
- func NewRealValue(r float64) Value
- func NewStringValue(s string) Value
- func NewUndefinedValue() Value
- func Sum(values []Value) Value
- func (v Value) BoolValue() (bool, error)
- func (v Value) ClassAdValue() (*ClassAd, error)
- func (v Value) IntValue() (int64, error)
- func (v Value) IsBool() bool
- func (v Value) IsClassAd() bool
- func (v Value) IsError() bool
- func (v Value) IsInteger() bool
- func (v Value) IsList() bool
- func (v Value) IsNumber() bool
- func (v Value) IsReal() bool
- func (v Value) IsString() bool
- func (v Value) IsUndefined() bool
- func (v Value) ListValue() ([]Value, error)
- func (v Value) NumberValue() (float64, error)
- func (v Value) RealValue() (float64, error)
- func (v Value) String() string
- func (v Value) StringValue() (string, error)
- func (v Value) Type() ValueType
- func (v Value) Unparse() (string, bool)
- type ValueType
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrBuiltinName means the name is already a built-in, which a UDF may not shadow. ErrBuiltinName = errors.New("classad: name is a built-in") // ErrFunctionExists means the name is already registered as a UDF. ErrFunctionExists = errors.New("classad: function already registered") // ErrBadFunction means the registration itself is malformed: a nil function, a name no // expression could call, or an impossible arity. ErrBadFunction = errors.New("classad: invalid function registration") )
Registration failures a caller can act on differently, as sentinels rather than only as messages.
A loader registering a batch of functions wants to tell these apart: colliding with a built-in is a mistake in what it was asked to load, already-registered is usually a double-load it can ignore, and a malformed name or arity is a bug in the thing that produced them. Without sentinels a caller can only re-wrap the text, and text is not an interface.
Functions ¶
func All ¶
All returns an iterator over all ClassAds from an io.Reader. This function is compatible with Go 1.23+ range-over-function syntax.
Example usage (Go 1.23+):
file, _ := os.Open("jobs.classads")
defer file.Close()
for ad := range classad.All(file) {
// Process ad...
}
For earlier Go versions, use the traditional pattern:
reader := classad.NewReader(file)
for reader.Next() {
ad := reader.ClassAd()
// Process ad...
}
func AllOld ¶
AllOld returns an iterator over all old-style ClassAds from an io.Reader. This function is compatible with Go 1.23+ range-over-function syntax.
Example usage (Go 1.23+):
file, _ := os.Open("machines.classads")
defer file.Close()
for ad := range classad.AllOld(file) {
// Process ad...
}
func AllOldWithError ¶
AllOldWithError returns an iterator for old-style ClassAds that captures any error.
func AllOldWithIndex ¶
AllOldWithIndex returns an iterator over all old-style ClassAds with their index. This function is compatible with Go 1.23+ range-over-function syntax.
func AllWithError ¶
AllWithError returns an iterator that yields ClassAds and captures any error. Use this when you need error handling with the iterator pattern.
Example usage:
file, _ := os.Open("jobs.classads")
defer file.Close()
var err error
for ad := range classad.AllWithError(file, &err) {
// Process ad...
}
if err != nil {
log.Fatal(err)
}
func AllWithIndex ¶
AllWithIndex returns an iterator over all ClassAds with their index. This function is compatible with Go 1.23+ range-over-function syntax.
Example usage (Go 1.23+):
file, _ := os.Open("jobs.classads")
defer file.Close()
for i, ad := range classad.AllWithIndex(file) {
fmt.Printf("ClassAd #%d\n", i)
// Process ad...
}
func BuiltinFunctionName ¶ added in v0.38.0
BuiltinFunctionName reports whether name is one of this language's built-in functions. The comparison is case-insensitive, as a call is.
It answers the half of KnownFunctionName that CANNOT CHANGE while the process runs. The registry is append-only and filled at start-up, so "is this name taken" has a different answer before and after a loader runs, while "is this name a built-in" has one answer for the life of the binary. A caller deciding something it must not revisit later -- whether a name may be defined at all, as opposed to whether it may be registered right now -- wants this one.
func CompareStringsFold ¶ added in v0.27.0
CompareStringsFold compares two strings the way every ClassAd string comparison operator does: case-insensitively. All six of <, <=, >, >=, == and != route through it, while the identity operators =?= and =!= deliberately do not -- they are case SENSITIVE.
Exported for the vectorized executor, which compares a whole column at a time and so cannot afford to box each element and re-dispatch on the operator, but must still produce exactly what the tree-walking evaluator produces. Sharing the function is what makes that a fact rather than a hope.
func FoldConstants ¶ added in v0.2.0
FoldConstants returns e with its constant sub-expressions pre-computed (e.g. Memory > 2048*1024 becomes Memory > 2147483648), evaluating against an empty scope so attribute references are left intact. It is a thin bridge over the flattener (see ClassAd.Flatten) for query planners that pattern-match normalized expressions. Returns nil for a nil input.
The result evaluates exactly as e does in any scope. That is why CurrentTime is left as a reference: its value is the scope's own CurrentTime when the scope defines one, so it is not a constant (see FoldConstantsAt).
func FoldConstantsAt ¶ added in v0.32.0
FoldConstantsAt is FoldConstants that also folds the magic CurrentTime attribute (an unscoped or MY reference) to now. The result evaluates as e does in a scope that does not define CurrentTime, at time now; in a scope that defines it, it may not. A query planner uses it to turn `CompletionDate > CurrentTime - 86400` into a range probe.
func GetAs ¶
GetAs retrieves and evaluates an attribute, converting it to the specified type. This is a type-safe generic getter that handles type conversions automatically. Returns the zero value and false if the attribute doesn't exist or conversion fails.
Example:
cpus, ok := classad.GetAs[int](ad, "cpus") name, ok := classad.GetAs[string](ad, "name") price, ok := classad.GetAs[float64](ad, "price") tags, ok := classad.GetAs[[]string](ad, "tags") config, ok := classad.GetAs[*classad.ClassAd](ad, "config")
func GetOr ¶
GetOr retrieves and evaluates an attribute with a default value. If the attribute doesn't exist or conversion fails, returns the default value. This is a type-safe generic getter with fallback.
Example:
cpus := classad.GetOr(ad, "cpus", 1) // Defaults to 1 name := classad.GetOr(ad, "name", "unknown") // Defaults to "unknown" timeout := classad.GetOr(ad, "timeout", 300) // Defaults to 300
func InsertAttrList ¶
func InsertAttrList[T int64 | float64 | string | bool | *ClassAd | *Expr](c *ClassAd, name string, values []T)
InsertAttrList inserts an attribute with a list of values using generics. Supported types are: int64, float64, string, bool, *ClassAd, and *Expr.
Example:
ad := classad.New()
InsertAttrList(ad, "numbers", []int64{1, 2, 3, 4, 5})
InsertAttrList(ad, "names", []string{"Alice", "Bob", "Charlie"})
InsertAttrList(ad, "flags", []bool{true, false, true})
InsertAttrList(ad, "values", []float64{1.5, 2.7, 3.14})
// Also works with ClassAds
ad1, ad2 := classad.New(), classad.New()
ad1.InsertAttr("x", 1)
ad2.InsertAttr("y", 2)
InsertAttrList(ad, "items", []*classad.ClassAd{ad1, ad2})
// And with expressions
expr1, _ := classad.ParseExpr("\"hello\"")
expr2, _ := classad.ParseExpr("42")
InsertAttrList(ad, "mixed", []*classad.Expr{expr1, expr2})
func IsCurrentTimeName ¶ added in v0.32.0
IsCurrentTimeName reports whether name is CurrentTime (case-insensitive), for a resolver (SetResolver) that must tell the magic attribute apart.
func IsCurrentTimeRef ¶ added in v0.32.0
func IsCurrentTimeRef(ref *ast.AttributeReference) bool
IsCurrentTimeRef reports whether ref names the magic CurrentTime attribute: an unscoped or MY reference, which evaluates to the current time when the scope does not define CurrentTime.
func IsPrivateAttribute ¶ added in v0.4.0
IsPrivateAttribute reports whether name is a private (secret) attribute of either kind, and so must not be serialized to a client by default. This is the predicate every serialization layer shares.
func IsPrivateAttributeV1 ¶ added in v0.4.0
IsPrivateAttributeV1 reports whether name is one of HTCondor's fixed private attributes (a claim capability or transfer key).
func IsPrivateAttributeV2 ¶ added in v0.4.0
IsPrivateAttributeV2 reports whether name is a "_condor_priv"-prefixed private attribute (matched case-insensitively).
func KnownFunctionName ¶ added in v0.38.0
KnownFunctionName reports whether name is already callable as a function: a built-in, or a user-defined function registered through RegisterFunction. The comparison is case-insensitive, as a call is.
It answers a WIDER question than StrictFunction, which reports whether a call of a given arity can be compiled natively and so says no to a lazy built-in, to a nondeterministic one and to a wrong argument count. A caller that wants to introduce a new name -- a second registry, a script's own function -- needs to know whether the name is taken at all, and StrictFunction returning false does not mean it is free.
func Marshal ¶
Marshal converts a Go value to a ClassAd string representation. It works similarly to encoding/json.Marshal but produces ClassAd format. Struct fields can use "classad" struct tags to control marshaling behavior. If no "classad" tag is present, it falls back to the "json" tag.
Supported struct tag options:
- Field name: classad:"custom_name" or json:"custom_name"
- Omit field: classad:"-" or json:"-"
- Omit if empty: classad:"name,omitempty" or json:"name,omitempty"
Example:
type Job struct {
ID int `classad:"JobId"`
Name string `classad:"Name"`
CPUs int `json:"cpus"` // falls back to json tag
Priority int // uses field name "Priority"
}
job := Job{ID: 123, Name: "test", CPUs: 4, Priority: 10}
classadStr, err := classad.Marshal(job)
// Result: [JobId = 123; Name = "test"; cpus = 4; Priority = 10]
func MarshalClassAd ¶
MarshalClassAd is an alias for Marshal for clarity
func Quote ¶
Quote escapes a string for safe use in ClassAd expressions. It adds surrounding quotes and escapes special characters according to ClassAd syntax.
Example:
quoted := classad.Quote(`value with "quotes"`) // Returns: "value with \"quotes\""
func RecoverCyclic ¶ added in v0.2.0
func RecoverCyclic(result *Value)
RecoverCyclic converts a cyclic-reference panic raised during evaluation into an error value, matching the tree-walker's top-level entry points. Use it as `defer classad.RecoverCyclic(&result)` around a bytecode run so a cyclic reference resolves to error rather than crashing.
This repeats recoverCyclic's body rather than calling it. recover() only stops a panic when the deferred function calls it DIRECTLY, and recoverCyclic cannot be inlined (the compiler refuses to inline any function calling recover), so delegating left recover() one frame too deep and it returned nil. Go <=1.25 papered over that; 1.26 does not, which turned every cyclic or over-deep expression reaching a vm entry point into a process-killing panic instead of an error value.
func RegisterFunction ¶ added in v0.35.0
RegisterFunction registers name as a user-defined function accepting minArgs..maxArgs arguments, where a negative maxArgs means variadic.
It fails rather than overwriting: a name that collides with a built-in or with an existing registration is an error. Shadowing a built-in would change what existing expressions mean, and silently replacing a registration would make the behaviour of a call depend on package initialization order.
func RegisteredFunctions ¶ added in v0.35.0
func RegisteredFunctions() []string
RegisteredFunctions returns the registered names, as registered, for diagnostics. The order is unspecified.
func SplitStringList ¶ added in v0.34.3
SplitStringList splits a delimited string list exactly as the stringList built-ins split it: on any rune in delimiter, with each element trimmed of surrounding space, and with ", " as the delimiter set when delimiter is empty.
It exists so a compiler can split a CONSTANT list once instead of per record, without reimplementing the split. stringListMember re-splits its list argument on every call, which for a literal list is the same work repeated for every ad in a scan.
func StrictFunction ¶ added in v0.34.1
StrictFunction reports whether a call to name with argc arguments can be compiled to an ApplyFunction call on pre-evaluated argument values -- that is, whether the function is known, accepts that argument count, and is strict, pure and independent of the calling scope.
A compiler must treat false as "delegate this call to the tree-walking evaluator", never as "this is an error". A false answer covers three different situations that happen to share a handling: a lazy or scope-dependent built-in (see nonStrictFunctions), an unknown function name, and a known function called with the wrong number of arguments. The last two produce ERROR *without evaluating the arguments*, which a compiled call cannot reproduce, because evaluateFunctionCall checks arity before it evaluates anything -- so pow(A0) with a self-referential A0 is error rather than a cyclic-reference failure. Delegating gets all three right by construction.
Names are matched case-insensitively, as the reference engine matches them.
A registered USER-DEFINED function is accepted on the same terms as a built-in, which is what makes a UDF compile natively and stay eligible for the columnar accelerators. Built-ins are consulted first; RegisterFunction refuses a name that collides with one, so the order only matters as a statement of precedence.
func StringListArg ¶ added in v0.34.3
StringListArg coerces a value to the string a stringList built-in treats it as: a string is itself, UNDEFINED is the empty string, and anything else is not usable (ok=false), which those built-ins report as ERROR.
Note an undefined item does NOT match a list that looks like it has an empty element: the split uses strings.FieldsFunc, which drops empty fields, so "a,,b" is two elements and stringListMember(undefined, "a,,b") is FALSE. The empty string is only ever found in a list that is itself empty of elements, which no list is. That is worth stating because the opposite is the obvious guess.
func Unmarshal ¶
Unmarshal parses a ClassAd string and stores the result in the value pointed to by v. It works similarly to encoding/json.Unmarshal but expects ClassAd format. Struct fields can use "classad" struct tags to control unmarshaling behavior. If no "classad" tag is present, it falls back to the "json" tag.
Example:
type Job struct {
ID int `classad:"JobId"`
Name string `classad:"Name"`
}
var job Job
err := classad.Unmarshal("[JobId = 123; Name = \"test\"]", &job)
func UnmarshalClassAd ¶
UnmarshalClassAd is an alias for Unmarshal for clarity
Types ¶
type ClassAd ¶
type ClassAd struct {
// contains filtered or unexported fields
}
ClassAd represents a ClassAd with attributes that can be evaluated. This is the main type for working with ClassAds.
A ClassAd is safe for concurrent reads: any number of goroutines may serialize, compare, look up, iterate and evaluate one ad at once, provided none of them writes it. The writes are Insert and its InsertAttr*/InsertExpr/InsertListElement/Set forms, Delete, Clear, UnmarshalJSON, SetParent and SetTarget -- and therefore NewMatchClassAd, ReplaceLeftAd and ReplaceRightAd, which call SetTarget on the ads they are given. A write needs exclusive access: no other goroutine may read or write the ad until it returns. See the package documentation.
func FromAST ¶ added in v0.2.0
FromAST wraps an ast.ClassAd in a ClassAd. The ast.ClassAd is adopted (not copied): FromAST may reorder its attributes into sorted order and collapse duplicate names, and callers should not mutate it afterward. It is the inverse of AST for serialization layers that decode to an ast.ClassAd.
func NewView ¶ added in v0.37.0
NewView wraps a in a read-only ClassAd that does NOT build the name index an owned ad keeps (see the index field): lookups scan a's attributes with a case-folding comparison instead, which allocates nothing at all. Building the index costs a map plus one lowercased key per attribute, which is the right trade for an ad that is looked up many times, and the wrong one for a handful of attributes read once -- the shape the evaluator already treats this way for a nested record literal.
a is NOT copied, and the view must be treated as read-only by its caller: the first write detaches it onto a private copy (see own), so a's attributes are never modified through the view, but a view built over a slice the caller goes on to reuse reads whatever that slice holds at the time. Callers that reuse a backing array between views must therefore be done with one view before refilling it.
Unlike FromAST, a view neither sorts nor deduplicates a: a repeated name resolves to its LAST assignment, matching the last-assignment-wins rule.
func ParseOld ¶
ParseOld parses a ClassAd in the "old" HTCondor format and returns a ClassAd object. Old ClassAds have attributes separated by newlines without surrounding brackets. Example:
Foo = 3 Bar = "hello" Moo = Foo =!= Undefined
func (*ClassAd) AST ¶ added in v0.2.0
AST returns the underlying ast.ClassAd. It is intended for serialization layers (e.g. collections/wire) that need the attribute expressions directly. The returned value aliases the ClassAd's internal storage and must not be mutated; attributes are sorted by normalized name. When the ad's own attribute list is not in that order, the result is a sorted copy of it (built once, and shared by later calls until the ad is written).
func (*ClassAd) Delete ¶
Delete removes an attribute from the ClassAd. Returns true if the attribute was found and deleted.
func (*ClassAd) Equal ¶
Equal reports whether two ClassAds have the same attributes and values, ignoring attribute order and casing of attribute names.
func (*ClassAd) EvaluateAttr ¶
EvaluateAttr evaluates an attribute and returns its value.
func (*ClassAd) EvaluateAttrBool ¶
EvaluateAttrBool evaluates an attribute as a boolean. Returns true if the attribute evaluated to a boolean.
func (*ClassAd) EvaluateAttrInt ¶
EvaluateAttrInt evaluates an attribute as an integer. Returns true if the attribute evaluated to an integer.
func (*ClassAd) EvaluateAttrNumber ¶
EvaluateAttrNumber evaluates an attribute as a number (int or real). Returns true if the attribute evaluated to a number. Integers are promoted to float64.
func (*ClassAd) EvaluateAttrReal ¶
EvaluateAttrReal evaluates an attribute as a real number. Returns true if the attribute evaluated to a real.
func (*ClassAd) EvaluateAttrString ¶
EvaluateAttrString evaluates an attribute as a string. Returns true if the attribute evaluated to a string.
func (*ClassAd) EvaluateExpr ¶
EvaluateExpr evaluates an arbitrary expression in the context of this ClassAd.
func (*ClassAd) EvaluateExprAgainst ¶ added in v0.31.5
EvaluateExprAgainst evaluates expr with this ClassAd as MY and target as TARGET, pairing them as NewMatchClassAd does -- within target's attributes, TARGET is this ad -- but for this evaluation only: neither ad is modified, so many goroutines may evaluate against one shared target (a cached slot ad, say) at once. NewMatchClassAd instead records each ad as the other's TARGET on the ads themselves, which is a write to both.
Example:
expr, _ := parser.ParseExpr("TARGET.Memory >= RequestMemory")
v := jobAd.EvaluateExprAgainst(expr, slotAd)
func (*ClassAd) EvaluateExprString ¶
EvaluateExprString parses and evaluates an expression string.
func (*ClassAd) EvaluateExprWithTarget ¶
EvaluateExprWithTarget evaluates an Expr in the context of this ClassAd with a target. This ClassAd serves as the MY scope, and the target parameter serves as the TARGET scope. This is useful for match-making operations where expressions reference both ClassAds.
Example:
expr, _ := classad.ParseExpr("MY.Cpus > TARGET.Cpus")
result := jobAd.EvaluateExprWithTarget(expr, machineAd)
func (*ClassAd) ExternalRefs ¶
ExternalRefs returns a list of attribute names referenced in the expression but not defined in this ClassAd. This is useful for validating that a ClassAd has all required attributes before evaluation.
Example:
ad, _ := classad.Parse("[Cpus = 4; Memory = 8192]")
expr, _ := classad.ParseExpr("Cpus * 2 + ExternalAttr")
external := ad.ExternalRefs(expr) // Returns: ["ExternalAttr"]
func (*ClassAd) Flatten ¶
Flatten partially evaluates an expression in the context of this ClassAd. Attributes that are defined in the ClassAd are evaluated and replaced with their values. Undefined attributes are left as references. This is useful for optimizing expressions by pre-computing constant sub-expressions.
Example:
ad, _ := classad.Parse("[RequestMemory = 2048]")
expr, _ := classad.ParseExpr("RequestMemory * 1024 * 1024")
flattened := ad.Flatten(expr) // Returns expression equivalent to: 2147483648
func (*ClassAd) GetAttributes ¶
GetAttributes returns a list of all attribute names, in the order the ad serializes them (sorted case-insensitively).
func (*ClassAd) InsertAttr ¶
InsertAttr inserts an attribute with an integer value.
func (*ClassAd) InsertAttrBool ¶
InsertAttrBool inserts an attribute with a boolean value.
func (*ClassAd) InsertAttrClassAd ¶
InsertAttrClassAd inserts an attribute with a nested ClassAd value. The provided ClassAd will be embedded as a record literal.
func (*ClassAd) InsertAttrFloat ¶
InsertAttrFloat inserts an attribute with a float value.
func (*ClassAd) InsertAttrString ¶
InsertAttrString inserts an attribute with a string value.
func (*ClassAd) InsertExpr ¶
InsertExpr inserts an attribute with an Expr value into the ClassAd. This allows you to copy expressions between ClassAds without evaluating them.
Example:
expr, _ := sourceAd.Lookup("Formula")
targetAd.InsertExpr("Formula", expr)
func (*ClassAd) InsertListElement ¶
InsertListElement inserts an element into a list attribute. If the attribute doesn't exist, it creates a new list with the element. If the attribute exists and is a list, it appends the element to the existing list. If the attribute exists but is not a list, it replaces it with a new list containing the element.
Example:
ad := classad.New()
expr1, _ := classad.ParseExpr("\"first\"")
expr2, _ := classad.ParseExpr("\"second\"")
ad.InsertListElement("items", expr1)
ad.InsertListElement("items", expr2)
// Result: items = {"first", "second"}
func (*ClassAd) InternalRefs ¶
InternalRefs returns a list of attribute names referenced in the expression that are defined in this ClassAd.
Example:
ad, _ := classad.Parse("[Cpus = 4; Memory = 8192]")
expr, _ := classad.ParseExpr("Cpus * 2 + ExternalAttr")
internal := ad.InternalRefs(expr) // Returns: ["Cpus"]
func (*ClassAd) Lookup ¶
Lookup returns the unevaluated expression for an attribute. Returns nil if the attribute doesn't exist. This is useful for inspecting or copying expressions without evaluating them.
Example:
ad, _ := classad.Parse("[x = 10; y = x * 2]")
expr, ok := ad.Lookup("y") // Returns expression for "x * 2"
if ok {
fmt.Println(expr.String()) // Prints: x * 2
}
func (*ClassAd) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface for ClassAd. ClassAds are serialized as JSON objects where:
- Attribute names are JSON keys
- Simple values (strings, numbers, booleans) are JSON values
- Lists are JSON arrays
- Nested ClassAds are JSON objects
- Expressions are serialized as strings with the format "/Expr(<expression>)/" (which appears as "\/Expr(<expression>)\/" in JSON due to escaping)
Example:
ad, _ := classad.Parse(`[x = 5; y = x + 3; name = "test"]`)
jsonBytes, _ := json.Marshal(ad)
// {"name":"test","x":5,"y":"\/Expr(x + 3)\/"}
MarshalJSON implements json.Marshaler, excluding private (secret) attributes so that any HTTP/JSON response that marshals a ClassAd is default-safe -- a job's ClaimId or a slot's Capability never reaches a client through json.Marshal. Use MarshalJSONWithPrivate where the full ad is required. See IsPrivateAttribute.
func (*ClassAd) MarshalJSONWithPrivate ¶ added in v0.4.0
MarshalJSONWithPrivate is MarshalJSON including private attributes. Prefer MarshalJSON for anything client-facing.
func (*ClassAd) MarshalOld ¶
ToOldFormat serializes the ClassAd to old HTCondor format (newline-delimited). Old format has one attribute per line without surrounding brackets.
Example:
ad, _ := classad.Parse("[Cpus = 4; Memory = 8192]")
oldFmt := ad.MarshalOld()
// Returns: "Cpus = 4\nMemory = 8192"
MarshalOld excludes private (secret) attributes; use MarshalOldWithPrivate for the full ad. See IsPrivateAttribute.
func (*ClassAd) MarshalOldWithPrivate ¶ added in v0.4.0
MarshalOldWithPrivate is MarshalOld including private attributes. Prefer MarshalOld for anything client-facing.
func (*ClassAd) Redacted ¶ added in v0.4.0
Redacted returns a copy of the ClassAd with every private attribute removed (see IsPrivateAttribute), leaving the original -- and its stored secrets -- untouched. It is the explicit form to hand to a client where a boundary does not already redact. A nil ad (or one with no attributes) is returned as-is; the returned copy shares attribute values with the original and must be treated as read-only.
func (*ClassAd) Set ¶
Set is a generic method that accepts any Go value and inserts it as an attribute. This provides a more idiomatic alternative to the type-specific Insert* methods. Supported types: int/int64/etc., float64, string, bool, []T, *ClassAd, *Expr, and structs.
Example:
ad := classad.New()
ad.Set("cpus", 4) // int
ad.Set("name", "job-1") // string
ad.Set("price", 3.14) // float64
ad.Set("enabled", true) // bool
ad.Set("tags", []string{"a", "b"}) // slice
ad.Set("config", nestedClassAd) // *ClassAd
func (*ClassAd) SetParent ¶
SetParent sets the parent ClassAd for this ClassAd. The parent is used for PARENT.attr references during evaluation. SetParent is a write: see the package documentation.
func (*ClassAd) SetTarget ¶
SetTarget sets the target ClassAd for this ClassAd. The target is used for TARGET.attr references during evaluation. SetTarget is a write: see the package documentation.
func (*ClassAd) String ¶
String renders the ClassAd in new (bracketed) format, excluding private (secret) attributes -- the default-safe form for any output that may reach a client. Use StringWithPrivate where the full ad, including secrets, is required (internal diagnostics, an authorized private channel).
func (*ClassAd) StringWithPrivate ¶ added in v0.4.0
StringWithPrivate is String including private attributes. Prefer String for anything client-facing; see IsPrivateAttribute.
func (*ClassAd) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface for ClassAd. Deserializes JSON into a ClassAd, handling the special expression format. Strings matching the pattern "/Expr(<expression>)/" are parsed as expressions. Note: When unmarshaling from JSON, the Go json package automatically unescapes "\/Expr(...)\/" to "/Expr(...)/" so only the unescaped format is checked.
Example:
jsonStr := `{"name":"test","x":5,"y":"\/Expr(x + 3)\/"}`
var ad ClassAd
json.Unmarshal([]byte(jsonStr), &ad)
type CondState ¶ added in v0.34.2
type CondState uint8
CondState is how a condition value selects a branch, as the conditional constructs classify it.
func ConditionState ¶ added in v0.34.2
ConditionState classifies a condition value exactly as evaluateIfThenElse and evaluateConditional classify it, by delegating to the same logicalView the evaluator uses. A compiled executor needs this to lower a conditional to a branch without reimplementing the coercion -- "1 ? a : b" selects a, and a string condition is an error, neither of which is obvious.
What a caller does with each state is NOT the same for the two constructs, and the difference is not visible from here:
ifThenElse(c, t, f) CondUndef yields UNDEFINED and evaluates NEITHER branch.
c ? t : f CondUndef yields UNDEFINED but still evaluates BOTH
branches, because an error value in a branch is absorbed
while a cyclic self-reference must still propagate.
Both yield ERROR for CondError without evaluating either branch.
type Evaluator ¶
type Evaluator struct {
// contains filtered or unexported fields
}
Evaluator handles evaluation of ClassAd expressions.
func NewEvaluator ¶
NewEvaluator creates a new evaluator for the given ClassAd.
func (*Evaluator) ApplyBinaryOp ¶ added in v0.2.0
ApplyBinaryOp applies a binary operator to two already-evaluated operand values, returning the same result the tree-walking evaluator would for the corresponding *ast.BinaryOp. It covers arithmetic, comparison, bitwise, the meta-equality operators ("is"/"isnt"), and the logical operators ("&&"/"||").
For "&&"/"||" the caller is responsible for short-circuiting (see ShortCircuit): when both operands are supplied here, the full three-valued truth table is applied, which is correct only if the caller already decided the right operand had to be evaluated.
func (*Evaluator) ApplySubscript ¶ added in v0.38.0
ApplySubscript indexes an already-evaluated container with an already-evaluated index, returning the same value the tree-walking evaluator produces for the equivalent *ast.SubscriptExpr. It is the subscript counterpart of ApplyBinaryOp, and evaluateSubscriptExpr is this function plus the evaluation of its two operands, so the two cannot hold different ideas of what an index means.
e materializes a LAZY list element, which is evaluated in the scope the list value captured rather than in e's own, so only the indexed element is evaluated: {selfRef, x}[1] is x and does not cycle. Pass the evaluator the operands were evaluated with.
AN UNDEFINED OR ERROR CONTAINER SETTLES THE RESULT whatever the index is, so a caller that has already evaluated both operands gets the right value from this function alone. It does not get the right behaviour: the tree-walker never evaluates the index in that case, and evaluating one can panic on a cyclic reference. A compiled form skips the index the same way.
func (*Evaluator) ApplyUnaryOp ¶ added in v0.2.0
ApplyUnaryOp applies a unary operator to an already-evaluated operand value.
func (*Evaluator) Evaluate ¶
Evaluate evaluates an expression in the context of the ClassAd.
Depth is tracked to bound recursion (a cyclic reference or a pathologically deep expression panics with cyclicEvalError once maxEvalDepth is reached). The increment/decrement is done inline rather than with `defer e.depth--`: this function recurses once per AST node, and because a recover() sits in an ancestor frame (the recoverCyclic at every evaluation entry point) the Go compiler cannot open-code those defers, so a per-node defer put the whole tree-walk on the slow stack-defer path -- ~25% of matchmaking CPU. On the cyclic-panic path the decrement is skipped (depth is left inflated), which is harmless: every terminal entry point recovers into a fresh or SetScope-reset evaluator, and the one recover-and-continue caller (evalRecoveringCyclic, for lazy-list elements) saves and restores depth around each element.
func (*Evaluator) PinCurrentTime ¶ added in v0.32.0
PinCurrentTime makes a CurrentTime reference the scope does not define evaluate to now rather than to the clock's current reading, so every evaluation of a compiled query sees one time. now == 0 restores reading the clock. An ad that defines CurrentTime still supplies its own value.
func (*Evaluator) ResolveAlias ¶ added in v0.36.0
ResolveAlias resolves a qualified reference through the alias resolver. ok is false when none is installed, in which case the caller must fall back to evaluating the reference the ordinary way -- against a real record -- so a program carrying qualified references is never silently answered from a resolver that is not there.
func (*Evaluator) ResolveRef ¶ added in v0.2.0
func (e *Evaluator) ResolveRef(name string, scope ast.AttributeScope) Value
ResolveRef resolves an attribute reference (with the given scope) in the evaluator's ClassAd, exactly as the evaluator resolves an *ast.AttributeReference: scope-chain search for an unscoped name, MY/TARGET/PARENT handling, evaluation of the referenced attribute's expression, and cyclic-reference detection.
func (*Evaluator) ResolveRefNode ¶ added in v0.27.0
func (e *Evaluator) ResolveRefNode(ref *ast.AttributeReference) Value
ResolveRefNode is ResolveRef for a reference node the caller already has, so a compiled program can hold one per reference instead of building a fresh node per evaluation.
NewAttributeReference heap-allocates and calls strings.ToLower, and ResolveRef does both on EVERY resolution -- once per reference per record during a scan. That defeats the precomputed-fold optimization resolveAttributeReference documents (the folded name is meant to be computed at parse time), and for a custom resolver the fold is pure waste, since the resolver is handed the original-cased name and never sees the folded one.
ref must not be mutated by the caller after this returns; evaluation treats it as read-only, which is what lets one node be shared by every evaluation of a program, including concurrent ones.
func (*Evaluator) SetAliasResolver ¶ added in v0.36.0
SetAliasResolver installs (or clears, with nil) a resolver for QUALIFIED attribute references -- `alias.Attr`, where alias names one side of a join. While set, a program compiled with vm.CompileAliases resolves such a reference through fn(alias, name) rather than selecting a member out of a materialized record, so a join condition can be evaluated against two separately-stored rows with no composite ClassAd built.
alias is the INDEX of the alias in the list the program was compiled with, not its text: the match is made once, at compile time, so evaluation compares no names.
fn returns the attribute's value, or undefined when the named side does not define it -- which is also how an absent side reads, and deliberately so: a LEFT JOIN's unmatched row has no member for the inner side, and ClassAd's spelling of that is undefined for every attribute of it. The Evaluator is not safe for concurrent use.
func (*Evaluator) SetPartialResolver ¶ added in v0.38.0
func (e *Evaluator) SetPartialResolver(fn func(name string, scope ast.AttributeScope) (Value, bool))
SetPartialResolver installs (or clears, with nil) a resolver that may DECLINE. While set, every attribute reference is offered to fn(name, scope) first; ok=true makes fn's value the reference's value, and ok=false leaves the reference to be resolved exactly as it would be with nothing installed -- the full resolver if one is set (SetResolver), otherwise the ClassAd scope, with the scope chain, the MY/TARGET/PARENT rules, the evaluation of the referenced attribute's expression and the CurrentTime substitution all intact.
DECLINING IS THE WHOLE POINT. SetResolver replaces scope resolution outright, so a caller that can answer for only SOME names -- a script overlaying its locals on the ad -- has no way to say "not mine". Saying it by returning undefined is wrong twice over: undefined is a value an ad can hold, and CurrentTime reads an undefined answer as "the ad does not define it". A separate ok is the one answer those cases need.
THE OVERLAY DOES NOT REACH INSIDE AN ATTRIBUTE'S VALUE. While the ad's own expression for an attribute is evaluated, fn is not consulted: `A = B + 1` means the ad's B wherever A is read, whatever the overlay calls B. Nor does it reach a nested scope -- a lazy list element, a nested ad, countMatches' per-ad context -- because each of those evaluates in an evaluator of its own, which carries no resolver (see child). A caller whose names must be visible there has to arrange it some other way.
fn is called with the reference's original-cased name; names in ClassAd are matched case-insensitively, so fn must fold. The Evaluator is not safe for concurrent use, and neither is anything fn closes over.
func (*Evaluator) SetResolver ¶ added in v0.2.0
func (e *Evaluator) SetResolver(fn func(name string, scope ast.AttributeScope) Value)
SetResolver installs (or clears, with nil) a custom attribute resolver. While set, every attribute reference the evaluator resolves is delegated to fn(name, scope) instead of being looked up in the ClassAd scope, so a bytecode program can be evaluated against an alternate backing (e.g. an encoded ad) without materializing a ClassAd. fn should return the attribute's value, or undefined if absent. The Evaluator is not safe for concurrent use.
CurrentTime (IsCurrentTimeName) needs care, because whether the ad defines it matters, not only its value. The evaluator reads undefined from fn for an unscoped or MY CurrentTime as "the ad does not define it" and substitutes the time, so fn must not return undefined for a CurrentTime the ad defines as undefined. For TARGET and PARENT the evaluator returns fn's value as is, so fn must not return undefined for a CurrentTime a target or parent that exists lacks; that one is the time. A resolver that cannot give the value must make its caller evaluate the ad the ordinary way instead.
func (*Evaluator) SetScope ¶ added in v0.2.0
SetScope rebinds the evaluator to a new scope ClassAd and resets its recursion depth, so one Evaluator can be reused across many evaluations (e.g. a bytecode Matcher scanning a collection) instead of allocating a fresh one per ad.
Cyclic-reference state is tracked on the Evaluator, and each attribute evaluation pops its own marker on the way out (even when a cyclic panic unwinds), so nothing carries over between scopes; the reset of it and of depth here is a defensive guarantee. The Evaluator is not safe for concurrent use, but the ads it evaluates are only read, so many Evaluators may share them.
func (*Evaluator) ShortCircuit ¶ added in v0.2.0
ShortCircuit reports whether the left operand of a logical operator already determines the result without evaluating the right operand, mirroring the evaluator's short-circuit rules:
"&&": left false -> false ; left error -> error "||": left true -> true ; left error -> error
If done is true, result is the operator's value and the right operand must not be evaluated. If done is false, the caller must evaluate the right operand and combine with ApplyBinaryOp. This lets the interpreter reproduce short-circuit behaviour (including its interaction with cyclic references) exactly.
type Expr ¶
type Expr struct {
// contains filtered or unexported fields
}
Expr represents an unevaluated ClassAd expression. It provides methods to evaluate the expression in different contexts and to inspect its structure.
func ParseExpr ¶
ParseExpr parses a ClassAd expression string and returns an Expr object. This allows you to work with expressions without evaluating them immediately.
Example:
expr, err := classad.ParseExpr("Cpus * 2 + Memory / 1024")
if err != nil {
log.Fatal(err)
}
func ParseExprOld ¶ added in v0.29.14
ParseExprOld parses a standalone expression as HTCondor's ParseClassAdRvalExpr does, which reads config macro functions ($INT, $EVAL, ...), submit expressions and job_queue.log values. String literals have OLD-ClassAd semantics: an unrecognized escape sequence is kept literally rather than rejected (a filename in a TransferInput list carries an escaped comma or space, `"...\,\ ..."`, which ParseExpr would reject), and adjacent literals are not concatenated. Like libclassad, it ignores whatever follows a top-level conditional (a ? b : c). See parser.ParseExprOld.
func (*Expr) AST ¶ added in v0.34.3
AST returns the expression's syntax tree, for serialization layers (e.g. collections/wire) that measure or encode it directly, as ClassAd.AST does for a whole ad. The tree is shared with e and must not be mutated.
func (*Expr) Eval ¶
Eval evaluates the expression in the context of the given ClassAd. This is equivalent to calling classad.EvaluateExpr(expr).
func (*Expr) EvalWithContext ¶
EvalWithContext evaluates the expression with explicit MY (scope) and TARGET contexts. The scope parameter provides the context for MY.attr references. The target parameter provides the context for TARGET.attr references. Either parameter may be nil if not needed.
Example:
expr, _ := classad.ParseExpr("MY.Cpus > TARGET.Cpus")
result := expr.EvalWithContext(jobAd, machineAd)
func (*Expr) FoldConstants ¶ added in v0.32.0
FoldConstants returns the expression with its constant sub-expressions pre-computed (see the package-level FoldConstants). The result evaluates exactly as e does, in any scope.
func (*Expr) Unparse ¶ added in v0.34.0
Unparse renders the expression the way the reference ClassAd unparser does, which is what HTCondor writes into a job ad and what another ClassAd implementation will read back.
This is NOT what String returns. String is a debugging form: it parenthesises every binary operation, and it prints a real with %g, so the whole-number real 8.0 comes out as "8" and parses back as an INTEGER. Either difference makes a comparison against a ClassAd produced elsewhere fail on text that means the same thing -- or, in the real case, on text that no longer means the same thing at all.
Reach for this whenever the output leaves the process: a job ad, a wire message, a diff against another implementation. Callers previously had to get here by inserting into a scratch ClassAd, calling MarshalOld and stripping the "X = " prefix.
func (*Expr) UnparseOld ¶ added in v0.34.0
UnparseOld renders the expression in old-ClassAd form, which differs from Unparse only in string-literal escaping: the old format escapes the delimiter alone, so a Windows path or a regex survives a round trip instead of gaining a backslash each hop. See marshalOld.
type Func ¶ added in v0.35.0
Func is a user-defined function: a pure function of its argument values.
It must not panic. One that does is contained -- ApplyFunction converts it to ERROR rather than letting it reach a daemon's goroutine -- but a panic is not a way to report failure. Returning ERROR is.
type Marshaler ¶
Marshaler is the interface implemented by types that can marshal themselves into ClassAd format. This is similar to json.Marshaler.
type MatchClassAd ¶
type MatchClassAd struct {
// contains filtered or unexported fields
}
MatchClassAd represents a pair of ClassAds for matching. Inspired by the HTCondor C++ MatchClassAd implementation. See: https://github.com/htcondor/htcondor/blob/main/src/classad/classad/matchClassad.h
In HTCondor, matching typically involves a job ClassAd and a machine ClassAd. Each can reference the other using TARGET.attr syntax.
func NewMatchClassAd ¶
func NewMatchClassAd(left, right *ClassAd) *MatchClassAd
NewMatchClassAd creates a new MatchClassAd with two ClassAds. The left ClassAd can reference the right using TARGET.attr The right ClassAd can reference the left using TARGET.attr
The pairing is recorded ON THE ADS: NewMatchClassAd calls SetTarget on both, so it is a write to each of them -- no other goroutine may be reading either ad -- and the TARGET stays set after the MatchClassAd is discarded (callers rely on this to evaluate left.EvaluateExpr(...) directly afterwards). To evaluate against an ad other goroutines share, such as a cached slot ad, use ClassAd.EvaluateExprAgainst, which pairs the two for one evaluation without writing either.
func (*MatchClassAd) EvaluateAttrLeft ¶
func (m *MatchClassAd) EvaluateAttrLeft(name string) Value
EvaluateAttrLeft evaluates an attribute in the left ClassAd.
func (*MatchClassAd) EvaluateAttrRight ¶
func (m *MatchClassAd) EvaluateAttrRight(name string) Value
EvaluateAttrRight evaluates an attribute in the right ClassAd.
func (*MatchClassAd) EvaluateExprLeft ¶
func (m *MatchClassAd) EvaluateExprLeft(expr ast.Expr) Value
EvaluateExprLeft evaluates an expression in the context of the left ClassAd.
func (*MatchClassAd) EvaluateExprRight ¶
func (m *MatchClassAd) EvaluateExprRight(expr ast.Expr) Value
EvaluateExprRight evaluates an expression in the context of the right ClassAd.
func (*MatchClassAd) EvaluateRankLeft ¶
func (m *MatchClassAd) EvaluateRankLeft() (float64, bool)
EvaluateRankLeft evaluates the left ClassAd's rank expression. In HTCondor, Rank is used to prefer certain matches over others.
func (*MatchClassAd) EvaluateRankRight ¶
func (m *MatchClassAd) EvaluateRankRight() (float64, bool)
EvaluateRankRight evaluates the right ClassAd's rank expression.
func (*MatchClassAd) GetLeftAd ¶
func (m *MatchClassAd) GetLeftAd() *ClassAd
GetLeftAd returns the left ClassAd.
func (*MatchClassAd) GetRightAd ¶
func (m *MatchClassAd) GetRightAd() *ClassAd
GetRightAd returns the right ClassAd.
func (*MatchClassAd) Match ¶
func (m *MatchClassAd) Match() bool
Match checks if the ClassAds match using default "Requirements" attribute. This is equivalent to Symmetry("Requirements", "Requirements").
func (*MatchClassAd) ReplaceLeftAd ¶
func (m *MatchClassAd) ReplaceLeftAd(left *ClassAd)
ReplaceLeftAd replaces the left ClassAd. Updates TARGET references appropriately: like NewMatchClassAd, a write to both ads.
func (*MatchClassAd) ReplaceRightAd ¶
func (m *MatchClassAd) ReplaceRightAd(right *ClassAd)
ReplaceRightAd replaces the right ClassAd. Updates TARGET references appropriately: like NewMatchClassAd, a write to both ads.
func (*MatchClassAd) Symmetry ¶
func (m *MatchClassAd) Symmetry(leftReqAttr, rightReqAttr string) bool
Symmetry checks if both ClassAds' Requirements evaluate to true. This is the core matching operation in HTCondor. Returns true only if BOTH: - left.Requirements evaluates to true (with TARGET = right) - right.Requirements evaluates to true (with TARGET = left)
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader provides an iterator for parsing multiple ClassAds from an io.Reader. It supports both new-style (bracketed) and old-style (newline-delimited) formats. New-style ClassAds can be concatenated without delimiters or whitespace.
func NewOldReader ¶
NewOldReader creates a new Reader for parsing old-style ClassAds (newline-delimited). Each ClassAd is separated by a blank line. Example format:
Foo = 1 Bar = 2 Baz = 3 Qux = 4
func NewReader ¶
NewReader creates a new Reader for parsing new-style ClassAds (with brackets). ClassAds may be concatenated directly; whitespace and comments are optional. Example format:
[Foo = 1; Bar = 2] [Baz = 3; Qux = 4]
func (*Reader) ClassAd ¶
ClassAd returns the current ClassAd. This should be called after Next() returns true.
type Unmarshaler ¶
Unmarshaler is the interface implemented by types that can unmarshal a ClassAd representation of themselves. This is similar to json.Unmarshaler.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value represents the result of evaluating a ClassAd expression.
A Value is copied by value constantly -- on every bytecode stack push/pop and every operator call -- so it is kept small: the list payload (which is nine words and only used by list values) lives out-of-line behind the payload pointer, leaving a Value that is a scalar/string/classad in one compact struct.
The struct is four words laid out as a tagged union. Every payload a Value can carry is squeezed into two slots, and the slots are shared only ever pointer-with-pointer or scalar-with-scalar, never across the two:
- intVal is the non-pointer slot, shared by every scalar payload.
- strVal's DATA POINTER is the pointer slot, shared by the string's bytes, the *ClassAd of a ClassAdValue and the *listData of a ListValue.
Never crossing is not stylistic: Go's garbage collector decides which words of a value to scan from the STATIC type of the field, so a word that is sometimes a pointer and sometimes an integer is unrepresentable -- scanned, an integer is followed as a pointer; unscanned, a live object is freed. No amount of unsafe changes this, because the pointer map is baked into the type descriptor at compile time. strVal's data word is a pointer word in every layout it takes here, so the collector's view of a Value is correct whatever the tag says.
Four words is the floor for a Value that keeps strVal a real Go string, which is what preserves the property a core value type should not give up: two separately built "alice" values still compare equal, and a Value still works as a map key. The alternative -- splitting the string into a raw {data pointer, length} pair across the two slots -- reaches three words and is equally GC-legal, but it makes string values compare by ADDRESS instead of by characters, a silent change that the whole test suite passes straight through. Eight more bytes are not worth that. See payload for how the aliasing keeps ad and list equality working anyway.
func ApplyFunction ¶ added in v0.34.1
ApplyFunction calls a strict built-in on already-evaluated argument values, returning the same value the tree-walking evaluator would for the equivalent *ast.FunctionCall. It is the function-call counterpart of ApplyBinaryOp: the one place a compiled executor gets built-in semantics from, so it cannot diverge from classad.Eval by having its own copy.
e is used only to materialize a lazy LIST argument and never to resolve a free attribute reference (see applyBuiltin). Pass the evaluator the arguments were evaluated with, which is what makes the result identical to evaluating the call as an AST node. A caller that cannot have one may pass a scope-less evaluator if and only if no argument can be a list -- then the ten list-consuming built-ins return ERROR without consulting it.
The caller must have established StrictFunction(name, len(args)) first. Calling it for a name that fails that predicate does not panic -- a lazy built-in is simply applied eagerly and an unknown one returns ERROR -- but the result is then not necessarily what evaluating the expression would have produced, which is the whole property this surface exists to preserve.
func Max ¶ added in v0.6.0
Max returns the numeric maximum under the ClassAd coercion rules (see Sum).
func Min ¶ added in v0.6.0
Min returns the numeric minimum under the ClassAd coercion rules (see Sum).
func NewClassAdValue ¶
NewClassAdValue creates a ClassAd value.
func NewUndefinedValue ¶
func NewUndefinedValue() Value
NewUndefinedValue creates an undefined value.
func Sum ¶ added in v0.6.0
Sum, Avg, Min, and Max apply HTCondor's ClassAd list-aggregate coercion rules (the sum()/avg()/min()/max() built-ins) to a slice of values: integers stay exact int64 and coerce to real only when a real value is present, booleans coerce to 0/1, undefined elements are skipped, and any error element makes the result an error. min/max are numeric (a string element is an error). An empty or all-undefined list sums/averages to integer 0; min/max of one is undefined. These let callers outside the expression evaluator (e.g. a GROUP BY engine) aggregate with identical semantics.
func (Value) ClassAdValue ¶
ClassAdValue returns the ClassAd value. Returns error if not a ClassAd.
func (Value) IsUndefined ¶
IsUndefined returns true if the value is undefined.
func (Value) NumberValue ¶
NumberValue returns the numeric value as a float64, converting integers if needed.
func (Value) StringValue ¶
StringValue returns the string value. Returns error if not a string.
func (Value) Unparse ¶ added in v0.31.4
Unparse renders v as the reference unparser does (ClassAdUnParser::Unparse of a Value): strings quoted and escaped, reals as "%1.15E" ("0.0" for zero), lists as "{ e1,e2 }", nested classads as "[ a = 1; b = 2 ]", undefined and error as their keywords. ok is false for values it cannot render that way.
type ValueType ¶
type ValueType int
ValueType represents the type of a ClassAd value.
const ( // UndefinedValue represents an undefined value UndefinedValue ValueType = iota // ErrorValue represents an error value ErrorValue // BooleanValue represents a boolean value BooleanValue // IntegerValue represents an integer value IntegerValue // RealValue represents a real (float) value RealValue // StringValue represents a string value StringValue // ListValue represents a list value ListValue // ClassAdValue represents a nested ClassAd value ClassAdValue )