Documentation
¶
Index ¶
- Constants
- Variables
- func AddTypes(c Context, types ...Type)
- func All(elements []Value, predicate Predicate) bool
- func Any(elements []Value, predicate Predicate) bool
- func DoWithContext(ctx Context, actor func(Context))
- func Each(elements []Value, consumer Consumer)
- func Equals(a interface{}, b interface{}, g Guard) bool
- func Error(issueCode issue.Code, args issue.H) issue.Reported
- func Error2(location issue.Location, issueCode issue.Code, args issue.H) issue.Reported
- func Fork(c Context, doer ContextDoer)
- func Go(f ContextDoer)
- func IncludesAll(a interface{}, b interface{}, g Guard) bool
- func IndexFrom(slice interface{}, value interface{}, startPos int, g Guard) int
- func IsValidModuleName(moduleName string) bool
- func LogWarning(issueCode issue.Code, args issue.H)
- func MismatchError(pfx interface{}, expected Type, value Value) issue.Reported
- func ReverseIndexFrom(slice interface{}, value interface{}, endPos int, g Guard) int
- func StackTop() issue.Location
- func StringElements(l List) []string
- func ToPrettyString(t Value) string
- func ToString(t Value) string
- func ToString2(t Value, format FormatContext) string
- func ToString3(t Value, writer io.Writer)
- func ToString4(t Value, format FormatContext, writer io.Writer)
- func TypeMismatchError(pfx interface{}, expected Type, actual Type) issue.Reported
- func Warning(issueCode issue.Code, args issue.H) issue.Reported
- type Annotatable
- type AnnotatedMember
- type AnnotatedType
- type Annotation
- type ArrayLogger
- type Arrayable
- type Attribute
- type AttributeKind
- type AttributesInfo
- type BiConsumer
- type BiMapper
- type BiPredicate
- type Boolean
- type CallableGoMember
- type CallableMember
- type CallableObject
- type Collector
- type Comparator
- type Consumer
- type Context
- type ContextDoer
- type Creatable
- type DefiningLoader
- type DependencyLoader
- type DetailedTypeValue
- type Dispatch
- type DispatchCreator
- type DispatchFunction
- type DispatchFunctionWithBlock
- type Doer
- type EntryMapper
- type Equality
- type Float
- type Format
- type FormatContext
- type FormatMap
- type Function
- type Generalizable
- type Guard
- type HashKey
- type HashKeyValue
- type ImplementationRegistry
- type Indentation
- type Indexed
- type IndexedConsumer
- type Integer
- type InterfaceValue
- type InvokableValue
- type IteratorValue
- type Keyed
- type Lambda
- type List
- type Loader
- type LoaderEntry
- type LocalTypes
- type LocalTypesCreator
- type LogEntry
- type LogLevel
- type Logger
- type MapEntry
- type Mapper
- type ModuleLoader
- type Namespace
- type Newable
- type Number
- type ObjFunc
- type Object
- type ObjectType
- type OrderedMap
- type Parameter
- type ParameterizedType
- type ParentedLoader
- type PathType
- type Predicate
- type Producer
- type PuppetObject
- type RDetect
- type ReadableObject
- type Reflected
- type ReflectedType
- type Reflector
- type ReportedEntry
- type ResolvableFunction
- type ResolvableType
- type SerializeAsString
- type Signature
- type Sized
- type SizedType
- type SliceConsumer
- type SortableList
- type StreamHashKeyValue
- type StringType
- type StringValue
- type TagsAnnotation
- type TextEntry
- type Type
- type TypeMapper
- type TypeSet
- type TypeSetLoader
- type TypeWithCallableMembers
- type TypeWithContainedType
- type TypedName
- type URI
- type Value
- func AssertInstance(pfx interface{}, expected Type, value Value) Value
- func Call(c Context, name string, args []Value, block Lambda) Value
- func CopyValues(src []Value) []Value
- func Find(elements []Value, predicate Predicate) (Value, bool)
- func Map(elements []Value, mapper Mapper) []Value
- func NewWithBlock(c Context, receiver Value, args []Value, block Lambda) Value
- func Reduce(elements []Value, memo Value, reductor BiMapper) Value
- func Reject(elements []Value, predicate Predicate) []Value
- func Select(elements []Value, predicate Predicate) []Value
- type ValueConsumer
- type VariableState
- type VariableStates
- type Visitor
Examples ¶
- ImplementationRegistry
- ImplementationRegistry (Tags)
- Reflector (FuncWithContext)
- Reflector (FuncWithContextAndParam)
- Reflector (ReflectArray)
- Reflector (ReflectPType)
- Reflector (ReflectToArray)
- Reflector (ReflectToBytes)
- Reflector (ReflectToFloat)
- Reflector (ReflectToHash)
- Reflector (ReflectToInt)
- Reflector (ReflectToRegexp)
- Reflector (ReflectToTimespan)
- Reflector (ReflectToTimestamp)
- Reflector (ReflectToVersion)
- Reflector (TwoValueReturn)
- Reflector (TypeFromReflect)
- Reflector (TypeFromReflectInterface)
- Reflector (TypeSetFromReflect)
Constants ¶
const ( AttemptToRedefine = `PCORE_ATTEMPT_TO_REDEFINE` AttemptToRedefineType = `PCORE_ATTEMPT_TO_REDEFINE_TYPE` AttemptToSetUnsettable = `PCORE_ATTEMPT_TO_SET_UNSETTABLE` AttemptToSetWrongKind = `PCORE_ATTEMPT_TO_SET_WRONG_KIND` AttributeHasNoValue = `PCORE_ATTRIBUTE_HAS_NO_VALUE` AttributeNotFound = `PCORE_ATTRIBUTE_NOT_FOUND` BadTypeString = `PCORE_BAD_TYPE_STRING` BothConstantAndAttribute = `PCORE_BOTH_CONSTANT_AND_ATTRIBUTE` ConstantRequiresValue = `PCORE_CONSTANT_REQUIRES_VALUE` ConstantWithFinal = `PCORE_CONSTANT_WITH_FINAL` CtorNotFound = `PCORE_CTOR_NOT_FOUND` DuplicateKey = `PCORE_DUPLICATE_KEY` EmptyTypeParameterList = `PCORE_EMPTY_TYPE_PARAMETER_LIST` EqualityAttributeNotFound = `PCORE_EQUALITY_ATTRIBUTE_NOT_FOUND` EqualityNotAttribute = `PCORE_EQUALITY_NOT_ATTRIBUTE` EqualityOnConstant = `PCORE_EQUALITY_ON_CONSTANT` EqualityRedefined = `PCORE_EQUALITY_REDEFINED` Failure = `PCORE_FAILURE` FileNotFound = `PCORE_FILE_NOT_FOUND` FileReadDenied = `PCORE_FILE_READ_DENIED` GoFunctionError = `PCORE_GO_FUNCTION_ERROR` GoRuntimeTypeWithoutGoType = `PCORE_GO_RUNTIME_TYPE_WITHOUT_GO_TYPE` IllegalArgument = `PCORE_ILLEGAL_ARGUMENT` IllegalArguments = `PCORE_ILLEGAL_ARGUMENTS` IllegalArgumentCount = `PCORE_ILLEGAL_ARGUMENT_COUNT` IllegalArgumentType = `PCORE_ILLEGAL_ARGUMENT_TYPE` IllegalKindValueCombination = `PCORE_ILLEGAL_KIND_VALUE_COMBINATION` IllegalObjectInheritance = `PCORE_ILLEGAL_OBJECT_INHERITANCE` ImplAlreadyRegistered = `PCORE_IMPL_ALREADY_REGISTERED` InstanceDoesNotRespond = `PCORE_INSTANCE_DOES_NOT_RESPOND` ImpossibleOptional = `PCORE_IMPOSSIBLE_OPTIONAL` InvalidCharactersInName = `PCORE_INVALID_CHARACTERS_IN_NAME` InvalidHashKey = `PCORE_INVALID_MAP_KEY` InvalidJson = `PCORE_INVALID_JSON` InvalidRegexp = `PCORE_INVALID_REGEXP` InvalidSourceForGet = `PCORE_INVALID_SOURCE_FOR_GET` InvalidSourceForSet = `PCORE_INVALID_SOURCE_FOR_SET` InvalidStringFormatSpec = `PCORE_INVALID_STRING_FORMAT_SPEC` InvalidStringFormatDelimiter = `PCORE_INVALID_STRING_FORMAT_DELIMITER` InvalidStringFormatRepeatedFlag = `PCORE_INVALID_STRING_FORMAT_REPEATED_FLAG` InvalidTimezone = `PCORE_INVALID_TIMEZONE` InvalidTypedNameMapKey = `PCORE_INVALID_TYPED_NAME_MAP_KEY` InvalidUri = `PCORE_INVALID_URI` InvalidVersion = `PCORE_INVALID_VERSION` InvalidVersionRange = `PCORE_INVALID_VERSION_RANGE` IsDirectory = `PCORE_IS_DIRECTORY` MatchNotRegexp = `PCORE_MATCH_NOT_REGEXP` MatchNotString = `PCORE_MATCH_NOT_STRING` MemberNameConflict = `PCORE_MEMBER_NAME_CONFLICT` MissingRequiredAttribute = `PCORE_MISSING_REQUIRED_ATTRIBUTE` MissingTypeParameter = `PCORE_MISSING_TYPE_PARAMETER` NilArrayElement = `NIL_ARRAY_ELEMENT` NilHashKey = `NIL_HASH_KEY` NilHashValue = `NIL_HASH_VALUE` NoAttributeReader = `PCORE_NO_ATTRIBUTE_READER` NoCurrentContext = `PCORE_NO_CURRENT_CONTEXT` NoDefinition = `PCORE_NO_DEFINITION` NotExpectedTypeset = `PCORE_NOT_EXPECTED_TYPESET` NotInteger = `PCORE_NOT_INTEGER` NotParameterizedType = `PCORE_NOT_PARAMETERIZED_TYPE` NotSemver = `PCORE_NOT_SEMVER` NotSupportedByGoTimeLayout = `PCORE_NOT_SUPPORTED_BY_GO_TIME_LAYOUT` ObjectInheritsSelf = `PCORE_OBJECT_INHERITS_SELF` OverrideMemberMismatch = `PCORE_OVERRIDE_MEMBER_MISMATCH` OverrideTypeMismatch = `PCORE_OVERRIDE_TYPE_MISMATCH` OverriddenNotFound = `PCORE_OVERRIDDEN_NOT_FOUND` OverrideOfFinal = `PCORE_OVERRIDE_OF_FINAL` OverrideIsMissing = `PCORE_OVERRIDE_IS_MISSING` ParseError = `PCORE_PARSE_ERROR` SerializationAttributeNotFound = `PCORE_SERIALIZATION_ATTRIBUTE_NOT_FOUND` SerializationNotAttribute = `PCORE_SERIALIZATION_NOT_ATTRIBUTE` SerializationBadKind = `PCORE_SERIALIZATION_BAD_KIND` SerializationDefaultConvertedToString = `PCORE_SERIALIZATION_DEFAULT_CONVERTED_TO_STRING` SerializationRequiredAfterOptional = `PCORE_SERIALIZATION_REQUIRED_AFTER_OPTIONAL` SerializationUnknownConvertedToString = `PCORE_SERIALIZATION_UNKNOWN_CONVERTED_TO_STRING` TimespanBadFormatSpec = `PCORE_TIMESPAN_BAD_FORMAT_SPEC` CannotBeParsed = `PCORE_TIMESPAN_CANNOT_BE_PARSED` TimespanFormatSpecNotHigher = `PCORE_TIMESPAN_FORMAT_SPEC_NOT_HIGHER` TimestampCannotBeParsed = `PCORE_TIMESTAMP_CANNOT_BE_PARSED` TimestampTzAmbiguity = `PCORE_TIMESTAMP_TZ_AMBIGUITY` TypeMismatch = `PCORE_TYPE_MISMATCH` TypesetAliasCollides = `PCORE_TYPESET_ALIAS_COLLIDES` TypesetMissingNameAuthority = `PCORE_TYPESET_MISSING_NAME_AUTHORITY` TypesetReferenceBadType = `PCORE_TYPESET_REFERENCE_BAD_TYPE` TypesetReferenceDuplicate = `PCORE_TYPESET_REFERENCE_DUPLICATE` TypesetReferenceMismatch = `PCORE_TYPESET_REFERENCE_MISMATCH` TypesetReferenceOverlap = `PCORE_TYPESET_REFERENCE_OVERLAP` TypesetReferenceUnresolved = `PCORE_TYPESET_REFERENCE_UNRESOLVED` UnableToDeserializeType = `PCORE_UNABLE_TO_DESERIALIZE_TYPE` UnableToDeserializeValue = `PCORE_UNABLE_TO_DESERIALIZE_VALUE` UnableToReadFile = `PCORE_UNABLE_TO_READ_FILE` UnhandledPcoreVersion = `PCORE_UNHANDLED_PCORE_VERSION` UnknownFunction = `PCORE_UNKNOWN_FUNCTION` UnknownVariable = `PCORE_UNKNOWN_VARIABLE` UnreflectableType = `PCORE_UNREFLECTABLE_TYPE` UnreflectableValue = `PCORE_UNREFLECTABLE_VALUE` UnresolvedType = `PCORE_UNRESOLVED_TYPE` UnresolvedTypeOf = `PCORE_UNRESOLVED_TYPE_OF` UnsupportedStringFormat = `PCORE_UNSUPPORTED_STRING_FORMAT` WrongDefinition = `PCORE_WRONG_DEFINITION` )
const ( PuppetDataTypePath = PathType(`puppetDataType`) PuppetFunctionPath = PathType(`puppetFunction`) PlanPath = PathType(`plan`) TaskPath = PathType(`task`) )
const ( ALERT = LogLevel(`alert`) CRIT = LogLevel(`crit`) DEBUG = LogLevel(`debug`) EMERG = LogLevel(`emerg`) ERR = LogLevel(`error`) INFO = LogLevel(`info`) NOTICE = LogLevel(`notice`) WARNING = LogLevel(`warning`) IGNORE = LogLevel(``) )
const ( KeyPcoreUri = `pcore_uri` KeyPcoreVersion = `pcore_version` RuntimeNameAuthority = URI(`http://puppet.com/2016.1/runtime`) PcoreUri = URI(`http://puppet.com/2016.1/pcore`) )
const Global = VariableState(1)
const Local = VariableState(2)
const NotFound = VariableState(0)
const NsAllocator = Namespace(`allocator`)
NsAllocator returns a function capable of allocating an instance of an object without initializing its content
const NsConstructor = Namespace(`constructor`)
NsConstructor denotes a function that both allocates an initializes an object based on parameter values
const NsDefinition = Namespace(`definition`)
NsDefinition denotes an entity that describes something that is provided by a remote service. Examples of such entities are callable API's and steps that can participate in a workflow.
const NsFunction = Namespace(`function`)
NsFunction denotes a callable function
const NsHandler = Namespace(`handler`)
NsHandler denotes a handler for a state in a workflow
const NsInterface = Namespace(`interface`)
NsInterface denotes an entity that must have an "interface" property that appoints an object type which in turn contains a declaration of the methods that the interface implements.
const NsPlan = Namespace(`plan`)
Here in case of future Bolt integration with the Evaluator
const NsService = Namespace(`service`)
NsService denotes a remote service
const NsStep = Namespace(`step`)
NsStep denotes a Puppet DSL specific step (not to be confused with a Definition of an step)
const NsTask = Namespace(`task`)
const NsType = Namespace(`type`)
NsType denotes a type in the Puppet type system
const PuppetContextKey = `puppet.context`
Variables ¶
var BuildFunction func(name string, localTypes LocalTypesCreator, creators []DispatchCreator) ResolvableFunction
var CommonType func(a Type, b Type) Type
var DefaultFor func(t Type) Type
var DescribeMismatch func(pfx string, expected Type, actual Type) string
DescribeMismatch returns a string that describes a mismatch between the expected and actual Type. The string is prefixed with the given pfx
var DescribeSignatures func(signatures []Signature, argsTuple Type, block Lambda) string
var DetailedValueType func(value Value) Type
var EmptyValues []Value
var FormatPattern = regexp.MustCompile(`\A%([\s\[+#0{<(|-]*)([1-9][0-9]*)?(?:\.([0-9]+))?([a-zA-Z])\z`)
var Generalize func(t Type) Type
var GenericType func(t Type) Type
var GenericValueType func(value Value) Type
var IsAssignable func(puppetType Type, other Type) bool
IsAssignable answers if t is assignable to this type
var IsInstance func(puppetType Type, value Value) bool
var IsTruthy func(tv Value) bool
var Load func(c Context, name TypedName) (interface{}, bool)
var MakeGoAllocator func(allocFunc DispatchFunction) Lambda
var MakeGoConstructor func(typeName string, creators ...DispatchCreator) ResolvableFunction
var MakeGoConstructor2 func(typeName string, localTypes LocalTypesCreator, creators ...DispatchCreator) ResolvableFunction
var New func(c Context, receiver Value, args ...Value) Value
New creates a new instance of type t
var NewAnnotatedType func(reflect.Type, map[string]string, OrderedMap) AnnotatedType
NewAnnotatedType returns a new instance of a AnnotatedType that is annotated
var NewCollector func() Collector
NewCollector returns a new Collector instance
var NewDependencyLoader func(depLoaders []ModuleLoader) Loader
var NewFileBasedLoader func(parent Loader, path, moduleName string, pathTypes ...PathType) ModuleLoader
var NewFormat func(format string) Format
var NewFormatContext func(t Type, format Format, indentation Indentation) FormatContext
var NewFormatContext2 func(indentation Indentation, formatMap FormatMap, properties map[string]string) FormatContext
var NewFormatContext3 func(value Value, format Value) (FormatContext, error)
var NewGoConstructor func(typeName string, creators ...DispatchCreator)
var NewGoConstructor2 func(typeName string, localTypes LocalTypesCreator, creators ...DispatchCreator)
var NewGoFunction func(name string, creators ...DispatchCreator)
var NewGoFunction2 func(name string, localTypes LocalTypesCreator, creators ...DispatchCreator)
var NewGoObjectType func(name string, rType reflect.Type, typeDecl string, creators ...DispatchFunction) ObjectType
NewGoObjectType is like NewObjectType but it is intended for Go types that do not implement the PuppetObject interface. Instead, the reflect.Type of the null value of a go instance is passed and later registered with the ImplementationRegistry. This helps Pcore to correctly compute the pcore Type of the go instance.
var NewGoType func(name string, zeroValue interface{}) ObjectType
NewGoType will infer the Pcore type from the public attributes and functions of the provided zeroValue which must be a struct or a pointer to a struct.
var NewIndentation func(indenting bool, level int) Indentation
var NewLoaderEntry func(value interface{}, origin issue.Location) LoaderEntry
var NewNamedType func(name, typeDecl string) Type
NewNamedType should be used to register an alias for another type.
var NewObjectType func(name, typeDecl string, creators ...DispatchFunction) ObjectType
NewObjectType creates a new ObjectType with the given name by parsing the provided pcore type definition.
When no creators are given, two constructor functions will be generated based on the attributes given in the type definition. The instance created by those functions will always be a struct types.attributeSlice.
Creators: A creator is responsible for creating an instance of the new type. The instance must implement the PuppetObject interface and its PType() function must return the type that is created by this function.
If one creator is given, then this creator can either be nil to prevent the construction of the default creators, or a creator that expects the args passed to be positional arguments for creating an instance.
If two creators are given, then the first creator must be a positional argument creator and the second a named argument creator. The named argument creator will always receive exactly one argument of type OrderedMap.
A special creator, the types.NoPositionalCreator can be used as the first creator when only a named argument creator is desired.
var NewParentedLoader func(parent Loader) DefiningLoader
var NewTaggedType func(reflect.Type, map[string]string) AnnotatedType
NewTaggedType returns a new instance of a AnnotatedType
var NewTypeSetLoader func(parent Loader, typeSet Type) TypeSetLoader
var NewTypedName func(namespace Namespace, name string) TypedName
var NewTypedName2 func(namespace Namespace, name string, nameAuthority URI) TypedName
var Normalize func(t Type) Type
var ParsablePcoreVersions, _ = semver.ParseVersionRange(`1.x`)
var PcoreVersion, _ = semver.NewVersion3(1, 0, 0, ``, ``)
var PuppetEquals func(a, b Value) bool
PuppetEquals is like Equals but:
int and float values with same value are considered equal string comparisons are case insensitive
var PuppetMatch func(lhs, rhs Value) bool
PuppetMatch tests if the LHS matches the RHS pattern expression and returns a Boolean result
When the RHS is a Type:
the match is true if the LHS is an instance of the type No match variables are set in this case.
When the RHS is a SemVerRange:
the match is true if the LHS is a SemVer, and the version is within the range the match is true if the LHS is a String representing a SemVer, and the version is within the range an error is raised if the LHS is neither a String with a valid SemVer representation, nor a SemVer. otherwise the result is false (not in range).
When the RHS is not a Type:
If the RHS evaluates to a String a new Regular Expression is created with the string value as its pattern. If the RHS is not a Regexp (after string conversion) an error is raised. If the LHS is not a String an error is raised. (Note, Numeric values are not converted to String automatically because of unknown radix).
var RegisterGoFunction func(function ResolvableFunction)
var RegisterResolvableType func(rt ResolvableType)
var ResolveResolvables func(c Context)
ResolveResolvables resolves types, constructions, or functions that has been recently added by init() functions
var ResolveTypes func(c Context, types ...ResolvableType)
Resolve
var SingletonMap func(string, Value) OrderedMap
var StaticLoader func() Loader
var ToArray func(elements []Value) List
ToArray returns a List consisting of the given elements
var ToFloat func(v Value) (float64, bool)
var ToInt func(v Value) (int64, bool)
var ToKey func(value Value) HashKey
var TypedNameFromMapKey func(mapKey string) TypedName
TypedNameFromMapKey recreates a TypedName from a given MapKey that was produced by a TypedName
var Wrap func(c Context, v interface{}) Value
Wrap converts the given value into a Value
var WrapReflected func(c Context, v reflect.Value) Value
WrapReflected converts the given reflect.Value into a Value
WrapReflectedType returns the pcore Type for a reflect.Type
Functions ¶
func All ¶
All passes each of the given elements to the given predicate. It returns true if the predicate never returns false.
func Any ¶
Any passes each of the given elements to the given predicate until the predicate returns true. The function then returns true. The function returns false when no predicate returns true.
func DoWithContext ¶
DoWithContext sets the given context to be the current context of the executing Go routine, calls the actor, and ensures that the old Context is restored once that call ends normally by panic.
func Equals ¶
Equals will compare two values for equality. If the first value implements the Equality interface, then the that interface is used. If the first value is a primitive, then the primitive will be compared using ==. The default behavior is to delegate to reflect.DeepEqual.
The comparison is optionally guarded from endless recursion by passing a Guard instance
func Error ¶
Error creates a Reported with the given issue code, location from stack top, and arguments Typical use is to panic with the returned value
func Error2 ¶
Error2 creates a Reported with the given issue code, location from stack top, and arguments Typical use is to panic with the returned value
func Fork ¶
func Fork(c Context, doer ContextDoer)
Fork calls the given function in a new go routine. The given context is forked and becomes the CurrentContext for that routine.
func Go ¶
func Go(f ContextDoer)
Go calls the given function in a new go routine. The CurrentContext is forked and becomes the CurrentContext for that routine.
func IncludesAll ¶
IncludesAll returns true if the given slice a contains all values in the given slice b.
func IndexFrom ¶
IndexFrom returns the index in the given slice of the first occurrence of an element for which Equals with the given value starting the comparison at the given startPos. The value of -1 is returned when no such element is found.
func IsValidModuleName ¶
func LogWarning ¶
LogWarning logs a warning to the logger of the current context
func ReverseIndexFrom ¶
ReverseIndexFrom returns the index in the given slice of the last occurrence of an element for which Equals with the given value between position zero and the given endPos. If endPos is -1 it will be set to the length of the slice.
The value of -1 is returned when no such element is found.
func StackTop ¶
StackTop returns the top of the stack contained in the current context or a location determined as the Go function that was the caller of the caller of this function, i.e. runtime.Caller(2).
func StringElements ¶
StringElements returns a slice containing each element in the given list as a string
func ToPrettyString ¶
func ToString2 ¶
func ToString2(t Value, format FormatContext) string
func TypeMismatchError ¶
Types ¶
type Annotatable ¶
type Annotatable interface {
Annotations(c Context) OrderedMap
}
type AnnotatedMember ¶
type AnnotatedMember interface {
Annotatable
Equality
CallableMember
Name() string
Label() string
FeatureType() string
Container() ObjectType
Type() Type
Override() bool
Final() bool
InitHash() OrderedMap
Accept(v Visitor, g Guard)
CallableType() Type
}
type AnnotatedType ¶
type AnnotatedType interface {
// Type returns the reflect.Type
Type() reflect.Type
// Annotations returns a map of annotations where each key is an Annotation type and the
// associated value is an instance of Init[<AnnotationType>].
Annotations() OrderedMap
// Tags returns a map, keyed by field names, containing values that are the
// 'puppet' tag parsed into an OrderedMap. The map is merged with possible
// overrides given when the AnnotatedType instance was created
Tags() map[string]OrderedMap
// Tags returns a map, keyed by field names, containing a map of all tags besides
// the 'puppet' tag
OtherTags() map[string]map[string]string
}
A AnnotatedType represent a reflect.Type with fields that may have 'puppet' tag overrides.
type Annotation ¶
type Annotation interface {
Validate(Context, Annotatable)
}
type ArrayLogger ¶
type ArrayLogger struct {
// contains filtered or unexported fields
}
func NewArrayLogger ¶
func NewArrayLogger() *ArrayLogger
func (*ArrayLogger) Entries ¶
func (l *ArrayLogger) Entries(level LogLevel) []LogEntry
func (*ArrayLogger) Log ¶
func (l *ArrayLogger) Log(level LogLevel, args ...Value)
func (*ArrayLogger) LogIssue ¶
func (l *ArrayLogger) LogIssue(i issue.Reported)
func (*ArrayLogger) Logf ¶
func (l *ArrayLogger) Logf(level LogLevel, format string, args ...interface{})
type Attribute ¶
type Attribute interface {
AnnotatedMember
Kind() AttributeKind
// Get returns this attributes value in the given instance
Get(instance Value) Value
// HasValue returns true if a value has been defined for this attribute.
HasValue() bool
// Default returns true if the given value equals the default value for this attribute
Default(value Value) bool
// Value returns the value of this attribute, or raises an error if no value has been defined.
Value() Value
// GoName Returns the name of the struct field that this attribute maps to when applicable or
// an empty string.
GoName() string
// Tags returns the TagAnnotation for this attribute or nil if the attribute has no tags.
Tags(Context) TagsAnnotation
}
type AttributeKind ¶
type AttributeKind string
type AttributesInfo ¶
type BiConsumer ¶
type BiPredicate ¶
type CallableGoMember ¶
type CallableGoMember interface {
// CallGo calls a member on a struct pointer with the given arguments
CallGo(c Context, receiver interface{}, args ...interface{}) []interface{}
// CallGoReflected is like Call but using reflected arguments and return value. The
// first argument is the receiver
CallGoReflected(c Context, args []reflect.Value) []reflect.Value
}
type CallableMember ¶
type CallableObject ¶
type CallableObject interface {
Call(c Context, method ObjFunc, args []Value, block Lambda) (result Value, ok bool)
}
CallableObject is implemented by PuppetObjects that have functions
type Collector ¶
type Collector interface {
ValueConsumer
// PopLast pops the last value from the BasicCollector and returns it
PopLast() Value
// Value returns the created value. Must not be called until the consumption
// of values is complete.
Value() Value
}
A Collector receives streaming events and produces an Value
type Comparator ¶
Comparator returns true when a is less than b.
type Context ¶
type Context interface {
context.Context
// Delete deletes the given key from the context variable map
Delete(key string)
// DefiningLoader returns a Loader that can receive new definitions
DefiningLoader() DefiningLoader
// DoWithLoader assigns the given loader to the receiver and calls the doer. The original loader is
// restored before this call returns.
DoWithLoader(loader Loader, doer Doer)
// Error creates a Reported with the given issue code, location, and arguments
// Typical use is to panic with the returned value
Error(location issue.Location, issueCode issue.Code, args issue.H) issue.Reported
// Fail creates a Reported with the EVAL_FAILURE issue code, location from stack top,
// and the given message
// Typical use is to panic with the returned value
Fail(message string) issue.Reported
// Fork a new context from this context. The fork will have the same scope,
// loaders, and logger as this context. The stack and the map of context variables will
// be shallow copied
Fork() Context
// Get returns the context variable with the given key together with a bool to indicate
// if the key was found
Get(key string) (interface{}, bool)
// ImplementationRegistry returns the registry that holds mappings between Type and reflect.Type
ImplementationRegistry() ImplementationRegistry
// Loader returns the loader of the receiver.
Loader() Loader
// Logger returns the logger of the receiver. This will be the same logger as the
// logger of the evaluator.
Logger() Logger
// ParseTypeValue parses and evaluates the given Value into a Type. It will panic with
// an issue.Reported unless the parsing was successful and the result is evaluates
// to a Type
ParseTypeValue(str Value) Type
// ParseType parses and evaluates the given string into a Type. It will panic with
// an issue.Reported unless the parsing was successful and the result is evaluates
// to a Type
ParseType(str string) Type
// Reflector returns a Reflector capable of converting to and from reflected values
// and types
Reflector() Reflector
// Scope returns an optional variable scope. This method is intended to be used when
// the context is used as an evaluation context. The method returns an empty OrderedMap
// by default.
Scope() Keyed
// Set adds or replaces the context variable for the given key with the given value
Set(key string, value interface{})
// Permanently change the loader of this context
SetLoader(loader Loader)
// Stack returns the full stack. The returned value must not be modified.
Stack() []issue.Location
// StackPop pops the last pushed location from the stack
StackPop()
// StackPush pushes a location onto the stack. The location is typically the
// currently evaluated expression.
StackPush(location issue.Location)
// StackTop returns the top of the stack
StackTop() issue.Location
}
An Context holds all state during evaluation. Since it contains the stack, each thread of execution must use a context of its own. It's expected that multiple contexts share common parents for scope and loaders.
func CurrentContext ¶
func CurrentContext() Context
CurrentContext returns the current runtime context or panics if no such context has been assigned
type ContextDoer ¶
type ContextDoer func(c Context)
type DefiningLoader ¶
type DefiningLoader interface {
Loader
SetEntry(name TypedName, entry LoaderEntry) LoaderEntry
}
type DependencyLoader ¶
type DependencyLoader interface {
Loader
LoaderFor(key string) ModuleLoader
}
type DetailedTypeValue ¶
type Dispatch ¶
type Dispatch interface {
// Name returns the name of the owner function
Name() string
Param(typeString string)
Param2(puppetType Type)
OptionalParam(typeString string)
OptionalParam2(puppetType Type)
RepeatedParam(typeString string)
RepeatedParam2(puppetType Type)
RequiredRepeatedParam(typeString string)
RequiredRepeatedParam2(puppetType Type)
Block(typeString string)
Block2(puppetType Type)
OptionalBlock(typeString string)
OptionalBlock2(puppetType Type)
Returns(typeString string)
Returns2(puppetType Type)
Function(f DispatchFunction)
Function2(f DispatchFunctionWithBlock)
}
Dispatch is a builder to build function dispatchers (Lambdas)
type DispatchCreator ¶
type DispatchCreator func(db Dispatch)
type DispatchFunction ¶
type EntryMapper ¶
type Equality ¶
type Equality interface {
// Returns true if the receiver is equal to the given value, false otherwise.
Equals(value interface{}, guard Guard) bool
}
Equality is implemented by values that can be compared for equality with other values
type Format ¶
type Format interface {
Value
HasStringFlags() bool
ApplyStringFlags(b io.Writer, str string, quoted bool)
Width() int
Precision() int
FormatChar() byte
Plus() byte
IsAlt() bool
IsLeft() bool
IsZeroPad() bool
LeftDelimiter() byte
ContainerFormats() FormatMap
Separator(dflt string) string
Separator2(dflt string) string
OrigFormat() string
ReplaceFormatChar(c byte) Format
WithoutWidth() Format
}
var DefaultFormat Format
type FormatContext ¶
type FormatContext interface {
Indentation() Indentation
FormatMap() FormatMap
Property(key string) (string, bool)
Properties() map[string]string
SetProperty(key, value string)
Subsequent() FormatContext
UnsupportedFormat(t Type, supportedFormats string, actualFormat Format) error
WithProperties(properties map[string]string) FormatContext
}
var DefaultFormatContext FormatContext
var Pretty FormatContext
var PrettyExpanded FormatContext
type FormatMap ¶
type FormatMap OrderedMap
type Function ¶
type Function interface {
InvokableValue
Dispatchers() []Lambda
Name() string
}
type Generalizable ¶
type Generalizable interface {
ParameterizedType
Generic() Type
}
Generalizable implemented by all parameterized types that have type parameters
type Guard ¶
type Guard map[visit]bool
Guard helps tracking endless recursion. The comparison algorithm assumes that all checks in progress are true when it encounters them again. Visited comparisons are stored in a map indexed by visit.
(algorithm copied from golang reflect/deepequal.go)
type HashKeyValue ¶
type HashKeyValue interface {
ToKey() HashKey
}
type ImplementationRegistry ¶
type ImplementationRegistry interface {
// RegisterType registers the mapping between the given Type and reflect.Type
RegisterType(t Type, r reflect.Type)
// TypeToReflected returns the reflect.Type for the given Type
TypeToReflected(t Type) (reflect.Type, bool)
// ReflectedToType returns the Type name for the given reflect.Type
ReflectedToType(t reflect.Type) (Type, bool)
// ReflectedNameToType returns the Type for the given Go Type name
ReflectedNameToType(name string) (Type, bool)
}
An ImplementationRegistry contains mappings between ObjectType and reflect.Type
Example ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/pcore/types"
)
func main() {
type TestAddress struct {
Street string
Zip string
}
type TestPerson struct {
Name string
Age int
Address *TestAddress
Active bool
}
address := types.Parse(`
attributes => {
street => String,
zip => String,
}`)
person := types.Parse(`
attributes => {
name => String,
age => Integer,
address => My::Address,
active => Boolean,
}`)
pcore.Do(func(c px.Context) {
px.AddTypes(c, types.NamedType(``, `My::Address`, address), types.NamedType(``, `My::Person`, person))
ir := c.ImplementationRegistry()
ir.RegisterType(c.ParseType(`My::Address`), reflect.TypeOf(TestAddress{}))
ir.RegisterType(c.ParseType(`My::Person`), reflect.TypeOf(TestPerson{}))
ts := &TestPerson{`Bob Tester`, 34, &TestAddress{`Example Road 23`, `12345`}, true}
ev := px.Wrap(c, ts)
fmt.Println(ev)
})
}
Output: My::Person('name' => 'Bob Tester', 'age' => 34, 'address' => My::Address('street' => 'Example Road 23', 'zip' => '12345'), 'active' => true)
Example (Tags) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/pcore/types"
)
func main() {
type TestAddress struct {
Street string
Zip string `puppet:"name=>zip_code"`
}
type TestPerson struct {
Name string
Age int
Address *TestAddress
Active bool `puppet:"name=>enabled"`
}
address := types.Parse(`
attributes => {
street => String,
zip_code => Optional[String],
}`)
person := types.Parse(`
attributes => {
name => String,
age => Integer,
address => My::Address,
enabled => Boolean,
}`)
pcore.Do(func(c px.Context) {
px.AddTypes(c, types.NamedType(``, `My::Address`, address), types.NamedType(``, `My::Person`, person))
ir := c.ImplementationRegistry()
ir.RegisterType(c.ParseType(`My::Address`), reflect.TypeOf(TestAddress{}))
ir.RegisterType(c.ParseType(`My::Person`), reflect.TypeOf(TestPerson{}))
ts := &TestPerson{`Bob Tester`, 34, &TestAddress{`Example Road 23`, `12345`}, true}
ev := px.Wrap(c, ts)
fmt.Println(ev)
})
}
Output: My::Person('name' => 'Bob Tester', 'age' => 34, 'address' => My::Address('street' => 'Example Road 23', 'zip_code' => '12345'), 'enabled' => true)
type Indentation ¶
type Indentation interface {
Breaks() bool
Increase(indenting bool) Indentation
IsFirst() bool
IsIndenting() bool
Indenting(indenting bool) Indentation
Level() int
Padding() string
Subsequent() Indentation
}
type IndexedConsumer ¶
type InterfaceValue ¶
type InterfaceValue interface {
Value
Interface() interface{}
}
type InvokableValue ¶
type IteratorValue ¶
type Lambda ¶
type Lambda interface {
InvokableValue
Parameters() []Parameter
Signature() Signature
}
type List ¶
type List interface {
Indexed
Add(Value) List
AddAll(List) List
All(predicate Predicate) bool
Any(predicate Predicate) bool
AppendTo(slice []Value) []Value
Delete(Value) List
DeleteAll(List) List
Each(Consumer)
EachSlice(int, SliceConsumer)
EachWithIndex(consumer IndexedConsumer)
Find(predicate Predicate) (Value, bool)
Flatten() List
Map(mapper Mapper) List
Select(predicate Predicate) List
Slice(i int, j int) List
Reduce(redactor BiMapper) Value
Reduce2(initialValue Value, redactor BiMapper) Value
Reject(predicate Predicate) List
Unique() List
}
List represents an Array. The iterative methods will not catch break exceptions. If
// that is desired, then use an Iterator instead.
var EmptyArray List
type Loader ¶
type Loader interface {
// GetEntry returns the requested entry from the internal cache of this loader
// without consulting parent loaders, or nil if no such entry can be found
GetEntry(name TypedName) LoaderEntry
// LoadEntry returns the requested entry or nil if no such entry can be found
LoadEntry(c Context, name TypedName) LoaderEntry
// NameAuthority returns the name authority
NameAuthority() URI
// Discover iterates over all entries accessible to this loader and its parents
// and returns a slice of all entries for which the provided function returns
// true
Discover(c Context, predicate func(tn TypedName) bool) []TypedName
// HasEntry returns true if this loader has an entry that maps to the give name
// The status of the entry is determined without actually loading it.
HasEntry(name TypedName) bool
}
type LoaderEntry ¶
type LocalTypes ¶
type LocalTypesCreator ¶
type LocalTypesCreator func(lt LocalTypes)
type Logger ¶
type Logger interface {
Log(level LogLevel, args ...Value)
Logf(level LogLevel, format string, args ...interface{})
LogIssue(issue issue.Reported)
}
func NewStdLogger ¶
func NewStdLogger() Logger
type ModuleLoader ¶
type ObjFunc ¶
type ObjFunc interface {
AnnotatedMember
// GoName Returns the name of the struct field that this attribute maps to when applicable or
// an empty string.
GoName() string
// ReturnsError returns true if the underlying method returns an error instance in case of
// failure. Such errors must be converted to panics by the caller
ReturnsError() bool
// TakesContext returns true if the first argument of the actual Go function
// is a context.Context
TakesContext() bool
}
type Object ¶
type Object interface {
Value
Initialize(c Context, arguments []Value)
InitFromHash(c Context, hash OrderedMap)
}
type ObjectType ¶
type ObjectType interface {
Annotatable
ParameterizedType
TypeWithCallableMembers
Creatable
HasHashConstructor() bool
Functions(includeParent bool) []ObjFunc
// Returns the Go reflect.Type that this type was reflected from, if any.
//
GoType() reflect.Type
// InstanceHash returns the InitHash for the given instance. The instance must be of this type
InstanceHash(o Value) OrderedMap
// IsInterface returns true for non parameterized types that contains only methods
IsInterface() bool
IsMetaType() bool
IsParameterized() bool
// Implements returns true the receiver implements all methods of ObjectType
Implements(ObjectType, Guard) bool
AttributesInfo() AttributesInfo
// FromReflectedValue creates a new instance of the receiver type
// and initializes that instance from the given src
FromReflectedValue(c Context, src reflect.Value) PuppetObject
// Parent returns the type that this type inherits from or nil if
// the type doesn't have a parent
Parent() Type
// ToReflectedValue copies values from src to dest. The src argument
// must be an instance of the receiver. The dest argument must be
// a reflected struct. The src must be able to deliver a value to
// each of the exported fields in dest.
//
// Puppets name convention stipulates lower case names using
// underscores to separate words. The Go conversion is to use
// camel cased names. ReflectValueTo will convert camel cased names
// into names with underscores.
ToReflectedValue(c Context, src PuppetObject, dest reflect.Value)
}
type OrderedMap ¶
type OrderedMap interface {
List
Keyed
AllPairs(BiPredicate) bool
AnyPair(BiPredicate) bool
AllKeysAreStrings() bool
Entries() List
EachKey(Consumer)
EachPair(BiConsumer)
EachValue(Consumer)
Get2(key Value, dflt Value) Value
Get3(key Value, dflt Producer) Value
Get4(key string) (Value, bool)
Get5(key string, dflt Value) Value
Get6(key string, dflt Producer) Value
// GetEntry returns the entry that represents the mapping between
// the given key and its value
GetEntry(key string) (entry MapEntry, found bool)
// GetEntryFold retuns the first entry that has a key which, in string form
// equals the given key using case insensitive comparison
GetEntryFold(key string) (entry MapEntry, found bool)
IncludesKey(o Value) bool
IncludesKey2(o string) bool
Keys() List
// MapEntries returns a new OrderedMap with both keys and values
// converted using the given mapper function
MapEntries(mapper EntryMapper) OrderedMap
// MapValues returns a new OrderedMap with the exact same keys as
// before but where each value has been converted using the given
// mapper function
MapValues(mapper Mapper) OrderedMap
Merge(OrderedMap) OrderedMap
// ToStringMap returns a copy of this map in the form of a Go map where all keys have been
// converted into strings
ToStringMap() map[string]Value
Values() List
SelectPairs(BiPredicate) OrderedMap
RejectPairs(BiPredicate) OrderedMap
}
OrderedMap represents a Hash. The iterative methods will not catch break exceptions. If that is desired, then use an Iterator instead.
var EmptyMap OrderedMap
type ParameterizedType ¶
type ParentedLoader ¶
type PuppetObject ¶
type PuppetObject interface {
Value
ReadableObject
InitHash() OrderedMap
}
type ReadableObject ¶
type Reflected ¶
type Reflected interface {
Reflect(c Context) reflect.Value
ReflectTo(c Context, value reflect.Value)
}
A Reflected is a value that can reflect itself into a given reflect.Value
type ReflectedType ¶
type ReflectedType interface {
Type
// ReflectType returns the reflect.Type that corresponds to the receiver
// if possible
ReflectType(c Context) (reflect.Type, bool)
}
A ReflectedType is implemented by PTypes that can have a potential to present themselves as a reflect.Type
type Reflector ¶
type Reflector interface {
// FieldName returns the puppet name for the given field. The puppet name is
// either picked from the 'puppet' tag of the field or the result of
// munging the field name through utils.FirstToLower
FieldName(f *reflect.StructField) string
// FunctionDeclFromReflect creates a function declaration suitable for inclusion in an ObjectType initialization
// hash.
FunctionDeclFromReflect(name string, mt reflect.Type, fromInterface bool) OrderedMap
// Reflect returns the reflected value of the native value held
// by the given src
Reflect(src Value) reflect.Value
// Reflect2 returns the reflected value of given type from the native value held
// by the given src
Reflect2(src Value, rt reflect.Type) reflect.Value
// ReflectFieldTags reflects the name, type, and value from a reflect.StructField
// using the field tags and the optionally given puppetTag
ReflectFieldTags(f *reflect.StructField, puppetTag OrderedMap, otherTags map[string]string) (name string, decl OrderedMap)
// ReflectTo assigns the native value of src to dest
ReflectTo(src Value, dest reflect.Value)
// ReflectType returns the reflected type of the given Type if possible. Only
// PTypes that represent a value can be represented as a reflected type. Types
// like Any, Default, Unit, or Variant have no reflected type representation
ReflectType(src Type) (reflect.Type, bool)
// InitializerFromTagged creates an Object initializer hash based on the given reflected type.
InitializerFromTagged(typeName string, parent Type, rType AnnotatedType) OrderedMap
// TypeFromReflect creates an ObjectType based on the given reflected type.
// The new type is automatically added to the ImplementationRegistry registered to
// the Context from where the Reflector was obtained.
TypeFromReflect(typeName string, parent Type, rType reflect.Type) ObjectType
// TypeFromTagged creates an Object type based on the given reflected type.
// The new type is automatically added to the ImplementationRegistry registered to
// the Context from where the Reflector was obtained.
TypeFromTagged(typeName string, parent Type, rType AnnotatedType, rcFunc Doer) ObjectType
// TypeSetFromReflect creates a TypeSet based on the given reflected types The new types are automatically
// added to the ImplementationRegistry registered to the Context from where the Reflector was obtained.
// The aliases map maps the names of the reflected types to the unqualified name of the created types.
// The aliases map may be nil and if present, may map only a subset of the reflected type names
TypeSetFromReflect(typeSetName string, version semver.Version, aliases map[string]string, rTypes ...reflect.Type) TypeSet
// TagHash returns the parsed and evaluated hash from the 'puppet' tag
TagHash(f *reflect.StructField) (OrderedMap, bool)
// Fields returns all fields of the given reflected type or an empty slice if no fields exists.
Fields(t reflect.Type) []reflect.StructField
// Methods returns all methods of the given reflected type or an empty slice if no methods exists.
Methods(ptr reflect.Type) []reflect.Method
}
A Reflector deals with conversions between Value and reflect.Value and between Type and reflect.Type
Example (FuncWithContext) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
type ctxParam struct {
}
func (t *ctxParam) FuncWithContext(c px.Context) string {
v, _ := c.Get(`testValue`)
return v.(string)
}
func (t *ctxParam) FuncWithContextAndParam(c px.Context, other string) string {
v, _ := c.Get(`testValue`)
return v.(string) + other
}
func main() {
pcore.Do(func(c px.Context) {
gv := &ctxParam{}
api := c.Reflector().TypeFromReflect(`A::B`, nil, reflect.TypeOf(gv))
px.AddTypes(c, api)
v := px.Wrap(c, gv)
r, _ := api.Member(`funcWithContext`)
c.Set(`testValue`, `hello world`)
fmt.Println(px.ToPrettyString(r.Call(c, v, nil, px.EmptyValues)))
})
}
Output: 'hello world'
Example (FuncWithContextAndParam) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/pcore/types"
)
type ctxParam struct {
}
func (t *ctxParam) FuncWithContext(c px.Context) string {
v, _ := c.Get(`testValue`)
return v.(string)
}
func (t *ctxParam) FuncWithContextAndParam(c px.Context, other string) string {
v, _ := c.Get(`testValue`)
return v.(string) + other
}
func main() {
pcore.Do(func(c px.Context) {
gv := &ctxParam{}
api := c.Reflector().TypeFromReflect(`A::B`, nil, reflect.TypeOf(gv))
px.AddTypes(c, api)
v := px.Wrap(c, gv)
r, _ := api.Member(`funcWithContextAndParam`)
c.Set(`testValue`, `hello world`)
fmt.Println(px.ToPrettyString(r.Call(c, v, nil, []px.Value{types.WrapString(`, what's up?`)})))
})
}
Output: 'hello world, what\'s up?'
Example (ReflectArray) ¶
package main
import (
"fmt"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/pcore/types"
)
func main() {
pcore.Do(func(c px.Context) {
av := px.Wrap(nil, []interface{}{`hello`, 3}).(*types.Array)
ar := c.Reflector().Reflect(av)
fmt.Printf("%s %v\n", ar.Type(), ar)
av = px.Wrap(nil, []interface{}{`hello`, `world`}).(*types.Array)
ar = c.Reflector().Reflect(av)
fmt.Printf("%s %v\n", ar.Type(), ar)
})
}
Output: []interface {} [hello 3] []string [hello world]
Example (ReflectPType) ¶
package main
import (
"fmt"
"os"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/pcore/types"
)
type valueStruct struct {
X px.OrderedMap
Y *types.Array
P px.PuppetObject
O px.Object
}
func (v *valueStruct) Get(key px.Integer, dflt px.Value) px.StringValue {
return v.X.Get2(key, px.Undef).(px.StringValue)
}
func main() {
pcore.Do(func(c px.Context) {
xm := c.Reflector().TypeFromReflect(`X::M`, nil, reflect.TypeOf(&valueStruct{}))
px.AddTypes(c, xm)
xm.ToString(os.Stdout, px.PrettyExpanded, nil)
fmt.Println()
})
}
Output: Object[{ name => 'X::M', attributes => { 'x' => Hash, 'y' => Array, 'p' => Object, 'o' => Object }, functions => { 'get' => Callable[ [Integer, Any], String] } }]
Example (ReflectToArray) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
func main() {
type TestStruct struct {
Strings []string
Interfaces []interface{}
Values []px.Value
}
pcore.Do(func(c px.Context) {
ts := &TestStruct{}
rv := reflect.ValueOf(ts).Elem()
av := px.Wrap(nil, []string{`hello`, `world`})
rf := c.Reflector()
rf.ReflectTo(av, rv.Field(0))
rf.ReflectTo(av, rv.Field(1))
rf.ReflectTo(av, rv.Field(2))
fmt.Println(ts)
rf.ReflectTo(px.Undef, rv.Field(0))
rf.ReflectTo(px.Undef, rv.Field(1))
rf.ReflectTo(px.Undef, rv.Field(2))
fmt.Println(ts)
})
}
Output: &{[hello world] [hello world] [hello world]} &{[] [] []}
Example (ReflectToBytes) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
func main() {
var buf []byte
pcore.Do(func(c px.Context) {
rf := c.Reflector()
bv := px.Wrap(nil, []byte{1, 2, 3})
rf.ReflectTo(bv, reflect.ValueOf(&buf).Elem())
fmt.Println(buf)
rf.ReflectTo(px.Undef, reflect.ValueOf(&buf).Elem())
fmt.Println(buf)
})
}
Output: [1 2 3] []
Example (ReflectToFloat) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
func main() {
type TestStruct struct {
SmallFloat float32
BigFloat float64
APValue px.Value
IValue interface{}
}
pcore.Do(func(c px.Context) {
rf := c.Reflector()
ts := &TestStruct{}
rv := reflect.ValueOf(ts).Elem()
n := rv.NumField()
for i := 0; i < n; i++ {
fv := px.Wrap(nil, float64(10+i+1)/10.0)
rf.ReflectTo(fv, rv.Field(i))
}
fmt.Println(ts)
})
}
Output: &{1.1 1.2 1.3 1.4}
Example (ReflectToHash) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
func main() {
var strings map[string]string
var interfaces map[string]interface{}
var values map[string]px.Value
pcore.Do(func(c px.Context) {
hv := px.Wrap(nil, map[string]string{`x`: `hello`, `y`: `world`})
rf := c.Reflector()
rf.ReflectTo(hv, reflect.ValueOf(&strings).Elem())
rf.ReflectTo(hv, reflect.ValueOf(&interfaces).Elem())
rf.ReflectTo(hv, reflect.ValueOf(&values).Elem())
fmt.Printf("%s %s\n", strings[`x`], strings[`y`])
fmt.Printf("%s %s\n", interfaces[`x`], interfaces[`y`])
fmt.Printf("%s %s\n", values[`x`], values[`y`])
rf.ReflectTo(px.Undef, reflect.ValueOf(&strings).Elem())
rf.ReflectTo(px.Undef, reflect.ValueOf(&interfaces).Elem())
rf.ReflectTo(px.Undef, reflect.ValueOf(&values).Elem())
fmt.Println(strings)
fmt.Println(interfaces)
fmt.Println(values)
})
}
Output: hello world hello world hello world map[] map[] map[]
Example (ReflectToInt) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
func main() {
type TestStruct struct {
AnInt int
AnInt8 int8
AnInt16 int16
AnInt32 int32
AnInt64 int64
AnUInt uint
AnUInt8 uint8
AnUInt16 uint16
AnUInt32 uint32
AnUInt64 uint64
APValue px.Value
IValue interface{}
}
pcore.Do(func(c px.Context) {
rf := c.Reflector()
ts := &TestStruct{}
rv := reflect.ValueOf(ts).Elem()
n := rv.NumField()
for i := 0; i < n; i++ {
rf.ReflectTo(px.Wrap(nil, 10+i), rv.Field(i))
}
fmt.Println(ts)
})
}
Output: &{10 11 12 13 14 15 16 17 18 19 20 21}
Example (ReflectToRegexp) ¶
package main
import (
"fmt"
"reflect"
"regexp"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
func main() {
pcore.Do(func(c px.Context) {
var expr regexp.Regexp
rx := px.Wrap(c, regexp.MustCompile("[a-z]*"))
c.Reflector().ReflectTo(rx, reflect.ValueOf(&expr).Elem())
fmt.Println(expr.String())
})
}
Output: [a-z]*
Example (ReflectToTimespan) ¶
package main
import (
"fmt"
"reflect"
"time"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
func main() {
pcore.Do(func(c px.Context) {
var span time.Duration
rx := px.Wrap(c, time.Duration(1234))
c.Reflector().ReflectTo(rx, reflect.ValueOf(&span).Elem())
fmt.Println(span)
})
}
Output: 1.234µs
Example (ReflectToTimestamp) ¶
package main
import (
"fmt"
"reflect"
"time"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
func main() {
pcore.Do(func(c px.Context) {
var tx time.Time
tm, _ := time.Parse(time.RFC3339, "2018-05-11T06:31:22+01:00")
tv := px.Wrap(c, tm)
c.Reflector().ReflectTo(tv, reflect.ValueOf(&tx).Elem())
fmt.Println(tx.Format(time.RFC3339))
})
}
Output: 2018-05-11T06:31:22+01:00
Example (ReflectToVersion) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/semver/semver"
)
func main() {
pcore.Do(func(c px.Context) {
var version semver.Version
ver, _ := semver.ParseVersion(`1.2.3`)
vv := px.Wrap(c, ver)
c.Reflector().ReflectTo(vv, reflect.ValueOf(&version).Elem())
fmt.Println(version)
})
}
Output: 1.2.3
Example (TwoValueReturn) ¶
package main
import (
"fmt"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
type twoValueReturn struct {
}
func (t *twoValueReturn) ReturnTwo() (string, int) {
return "number", 42
}
func (t *twoValueReturn) ReturnTwoAndErrorOk() (string, int, error) {
return "number", 42, nil
}
func (t *twoValueReturn) ReturnTwoAndErrorFail() (string, int, error) {
return ``, 0, fmt.Errorf(`bad things happened`)
}
func main() {
pcore.Do(func(c px.Context) {
gv := &twoValueReturn{}
api := c.Reflector().TypeFromReflect(`A::B`, nil, reflect.TypeOf(gv))
px.AddTypes(c, api)
v := px.Wrap(c, gv)
r, _ := api.Member(`returnTwo`)
fmt.Println(px.ToPrettyString(r.Call(c, v, nil, px.EmptyValues)))
})
}
Output: ['number', 42]
Example (TypeFromReflect) ¶
package main
import (
"fmt"
"os"
"reflect"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/pcore/types"
)
func main() {
type TestAddress struct {
Street string
Zip string
}
type TestPerson struct {
Name string
Address *TestAddress
}
type TestExtendedPerson struct {
TestPerson
Age *int `other:"stuff"`
Active bool `puppet:"name=>enabled"`
}
pcore.Do(func(c px.Context) {
rtAddress := reflect.TypeOf(&TestAddress{})
rtPerson := reflect.TypeOf(&TestPerson{})
rtExtPerson := reflect.TypeOf(&TestExtendedPerson{})
rf := c.Reflector()
tAddress := rf.TypeFromTagged(`My::Address`, nil, px.NewTaggedType(rtAddress, map[string]string{`Zip`: `name=>zip_code`}), nil)
tPerson := rf.TypeFromReflect(`My::Person`, nil, rtPerson)
tExtPerson := rf.TypeFromReflect(`My::ExtendedPerson`, tPerson, rtExtPerson)
px.AddTypes(c, tAddress, tPerson, tExtPerson)
tAddress.ToString(os.Stdout, types.Expanded, nil)
fmt.Println()
tPerson.ToString(os.Stdout, types.Expanded, nil)
fmt.Println()
tExtPerson.ToString(os.Stdout, types.Expanded, nil)
fmt.Println()
age := 34
ts := &TestExtendedPerson{TestPerson{`Bob Tester`, &TestAddress{`Example Road 23`, `12345`}}, &age, true}
ev := px.Wrap(c, ts)
fmt.Println(ev)
})
}
Output: Object[{name => 'My::Address', attributes => {'street' => String, 'zip_code' => String}}] Object[{name => 'My::Person', attributes => {'name' => String, 'address' => Optional[My::Address]}}] Object[{name => 'My::ExtendedPerson', parent => My::Person, attributes => {'age' => {'annotations' => {TagsAnnotation => {'other' => 'stuff'}}, 'type' => Optional[Integer]}, 'enabled' => Boolean}}] My::ExtendedPerson('name' => 'Bob Tester', 'enabled' => true, 'address' => My::Address('street' => 'Example Road 23', 'zip_code' => '12345'), 'age' => 34)
Example (TypeFromReflectInterface) ¶
package main
import (
"fmt"
"os"
"reflect"
"strconv"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
)
type A interface {
Int() int
X() string
Y(A) A
}
type B int
func NewA(x int) A {
return B(x)
}
func (b B) X() string {
return strconv.Itoa(int(b) + 5)
}
func (b B) Int() int {
return int(b)
}
func (b B) Y(a A) A {
return NewA(int(b) + a.Int())
}
func main() {
pcore.Do(func(c px.Context) {
// Create ObjectType from reflected type
xa := c.Reflector().TypeFromReflect(`X::A`, nil, reflect.TypeOf((*A)(nil)).Elem())
xb := c.Reflector().TypeFromReflect(`X::B`, nil, reflect.TypeOf(B(0)))
// Ensure that the type is resolved
px.AddTypes(c, xa, xb)
// Print the created Interface Type in human readable form
xa.ToString(os.Stdout, px.PrettyExpanded, nil)
fmt.Println()
// Print the created Implementation Type in human readable form
xb.ToString(os.Stdout, px.PrettyExpanded, nil)
fmt.Println()
// Invoke method 'x' on the interface on a receiver
m, _ := xb.Member(`x`)
gm := m.(px.CallableGoMember)
fmt.Println(gm.CallGo(c, NewA(32))[0])
fmt.Println(gm.CallGo(c, B(25))[0])
// Invoke method 'x' on the interface on a receiver
m, _ = xb.Member(`y`)
// Call Go function using CallableGoMember
gv := m.(px.CallableGoMember).CallGo(c, B(25), NewA(15))[0]
fmt.Printf("%T %v\n", gv, gv)
// Call Go function using CallableMember and pcore.Value
pv := m.Call(c, px.New(c, xb, px.Wrap(c, 25)), nil, []px.Value{px.New(c, xb, px.Wrap(c, 15))})
fmt.Println(pv)
})
}
Output: Object[{ name => 'X::A', functions => { 'int' => Callable[ [0, 0], Integer], 'x' => Callable[ [0, 0], String], 'y' => Callable[ [X::A], X::A] } }] Object[{ name => 'X::B', attributes => { 'value' => Integer }, functions => { 'int' => Callable[ [0, 0], Integer], 'x' => Callable[ [0, 0], String], 'y' => Callable[ [X::A], X::A] } }] 37 30 px_test.B 40 X::B('value' => 40)
Example (TypeSetFromReflect) ¶
package main
import (
"fmt"
"os"
"reflect"
"time"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/semver/semver"
)
type Address struct {
Street string
Zip string `puppet:"name=>zip_code"`
}
type Person struct {
Name string
Address *Address
}
type ExtendedPerson struct {
Person
Birth *time.Time
TimeSinceVisit *time.Duration
Active bool `puppet:"name=>enabled"`
}
func (p *Person) Visit(v *Address) string {
return "visited " + v.Street
}
func main() {
pcore.Do(func(c px.Context) {
// Create a TypeSet from a list of Go structs
typeSet := c.Reflector().TypeSetFromReflect(`My::Own`, semver.MustParseVersion(`1.0.0`), nil,
reflect.TypeOf(&Address{}), reflect.TypeOf(&Person{}), reflect.TypeOf(&ExtendedPerson{}))
// Make the types known to the current loader
px.AddTypes(c, typeSet)
// Print the TypeSet in human readable form
typeSet.ToString(os.Stdout, px.PrettyExpanded, nil)
fmt.Println()
// Create an instance of something included in the TypeSet
ad := &Address{`Example Road 23`, `12345`}
birth, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
tsv, _ := time.ParseDuration("1h20m")
ep := &ExtendedPerson{Person{`Bob Tester`, ad}, &birth, &tsv, true}
// Wrap the instance as a Value and print it
v := px.Wrap(c, ep)
fmt.Println(v)
m, _ := v.PType().(px.TypeWithCallableMembers).Member(`visit`)
fmt.Println(m.(px.CallableGoMember).CallGo(c, ep, ad)[0])
fmt.Println(m.Call(c, v, nil, []px.Value{px.Wrap(c, ad)}))
})
}
Output: TypeSet[{ pcore_uri => 'http://puppet.com/2016.1/pcore', pcore_version => '1.0.0', name_authority => 'http://puppet.com/2016.1/runtime', name => 'My::Own', version => '1.0.0', types => { Address => { attributes => { 'street' => String, 'zip_code' => String } }, Person => { attributes => { 'name' => String, 'address' => Optional[Address] }, functions => { 'visit' => Callable[ [Optional[Address]], String] } }, ExtendedPerson => Person{ attributes => { 'birth' => Optional[Timestamp], 'timeSinceVisit' => Optional[Timespan], 'enabled' => Boolean } } } }] My::Own::ExtendedPerson('name' => 'Bob Tester', 'enabled' => true, 'address' => My::Own::Address('street' => 'Example Road 23', 'zip_code' => '12345'), 'birth' => 2006-01-02T15:04:05.000000000 UTC, 'timeSinceVisit' => 0-01:20:00.0) visited Example Road 23 visited Example Road 23
type ReportedEntry ¶
type ReportedEntry struct {
// contains filtered or unexported fields
}
func (*ReportedEntry) Issue ¶
func (re *ReportedEntry) Issue() issue.Reported
func (*ReportedEntry) Level ¶
func (re *ReportedEntry) Level() LogLevel
func (*ReportedEntry) Message ¶
func (re *ReportedEntry) Message() string
type ResolvableFunction ¶
type ResolvableType ¶
type SerializeAsString ¶
type SerializeAsString interface {
// CanSerializeAsString responds true if this instance and all its nested
// instances can serialize as string
CanSerializeAsString() bool
// SerializationString returns the string that the type of the instance can use
// to recreate the instance
SerializationString() string
}
type Signature ¶
type Signature interface {
Type
CallableWith(args []Value, block Lambda) bool
ParametersType() Type
ReturnType() Type
// BlockType returns a Callable, Optional[Callable], or nil to denote if a
// block is required, optional, or invalid
BlockType() Type
// BlockName will typically return the string "block"
BlockName() string
// ParameterNames returns the names of the parameters. Will return the strings "1", "2", etc.
// for unnamed parameters.
ParameterNames() []string
}
type SliceConsumer ¶
type SliceConsumer func(value List)
type SortableList ¶
type SortableList interface {
List
Sort(comparator Comparator) List
}
type StreamHashKeyValue ¶
type StringType ¶
type StringValue ¶
type StringValue interface {
List
Split(pattern *regexp.Regexp) List
ToLower() StringValue
ToUpper() StringValue
EqualsIgnoreCase(Value) bool
}
type TagsAnnotation ¶
type TagsAnnotation interface {
PuppetObject
Tag(key string) string
Tags() OrderedMap
}
type Type ¶
type Type interface {
Value
IsInstance(o Value, g Guard) bool
IsAssignable(t Type, g Guard) bool
MetaType() ObjectType
Name() string
Accept(visitor Visitor, g Guard)
}
func AssertType ¶
type TypeMapper ¶
type TypeSet ¶
type TypeSet interface {
ParameterizedType
// GetType returns the given type from the receiver together with
// a flag indicating success or failure
GetType(typedName TypedName) (Type, bool)
// GetType2 is like GetType but uses a string to identify the type
GetType2(name string) (Type, bool)
// Authority returns the name authority of the receiver
NameAuthority() URI
// TypedName returns the name of this type set as a TypedName
TypedName() TypedName
// Types returns a hash of all types contained in this set. The keys
// in this hash are relative to the receiver name
Types() OrderedMap
// Version returns the version of the receiver
Version() semver.Version
}
type TypeSetLoader ¶
type TypeWithCallableMembers ¶
type TypeWithCallableMembers interface {
// Member returns an attribute reader or other function and true, or nil and false if no such member exists
Member(name string) (CallableMember, bool)
}
type TypeWithContainedType ¶
type TypedName ¶
type TypedName interface {
PuppetObject
issue.Named
IsParent(n TypedName) bool
IsQualified() bool
MapKey() string
Authority() URI
Namespace() Namespace
Parts() []string
// PartsList returns the parts as a List
PartsList() List
// Child returns the typed name with its leading segment stripped off, e.g.
// A::B::C returns B::C
Child() TypedName
// Parent returns the typed name with its final segment stripped off, e.g.
// A::B::C returns A::B
Parent() TypedName
RelativeTo(parent TypedName) (TypedName, bool)
}
type Value ¶
type Value interface {
fmt.Stringer
Equality
ToString(bld io.Writer, format FormatContext, g RDetect)
PType() Type
}
var EmptyString Value
var Undef Value
func AssertInstance ¶
func Call ¶
Call calls a function known to the loader of the Context with arguments and an optional block.
func CopyValues ¶
func Find ¶
Find passes each of the given elements to the given predicate and returns the first element for which the predicate returns true together with a boolean true. The function returns nil, false when no predicate returns true.
func Map ¶
Map passes each of the given elements to the given mapper and builds a new slice from the mapper return values. The new slice is returned.
func NewWithBlock ¶
New creates a new instance of type t and calls the block with the created instance. It returns the value returned from the block
func Reduce ¶
Reduce combines all elements of the given slice by applying a binary operation. For each element in teh slice, the reductor is passed an accumulator value (memo) and the element. The result becomes the new value for the memo. At the end of iteration, the final memo is returned.
type ValueConsumer ¶
type ValueConsumer interface {
// CanDoBinary returns true if the value can handle binary efficiently. This tells
// the Serializer to pass BinaryValue verbatim to Add
CanDoBinary() bool
// CanComplexKeys() returns true if complex values can be used as keys. If this
// method returns false, all keys must be strings
CanDoComplexKeys() bool
// StringDedupThreshold returns the preferred threshold for dedup of strings. Strings
// shorter than this threshold will not be subjected to de-duplication.
StringDedupThreshold() int
// AddArray starts a new array, calls the doer function, and then ends the Array.
//
// The callers reference index is increased by one.
AddArray(len int, doer Doer)
// AddHash starts a new hash., calls the doer function, and then ends the Hash.
//
// The callers reference index is increased by one.
AddHash(len int, doer Doer)
// Add adds the next value.
//
// Calls following a StartArray will add elements to the Array
//
// Calls following a StartHash will first add a key, then a value. This
// repeats until End or StartArray is called.
//
// The callers reference index is increased by one.
Add(element Value)
// Add a reference to a previously added afterElement, hash, or array.
AddRef(ref int)
}
A ValueConsumer is used by a Data streaming mechanism that maintains a reference index which is increased by one for each value that it streams. The reference index originates from zero.
type VariableState ¶
type VariableState int
type VariableStates ¶
type VariableStates interface {
// State returns NotFound, Global, or Local for the given name.
State(name string) VariableState
}
VariableStates is implemented by an evaluation scope that wishes to differentiate between local and global states. The difference is significant for modules like Hiera that relies on that global variables remain unchanged during evaluation.