package machineimport ()// ///// ///// /////// ///// STATES// ///// ///// /////// StatesBase is the base class for schema states definition, providing compiler// safety and holding order of state names, as well as groups.typeStatesBasestruct {// TODO rename to SchemaStates// TODO Prefix, support prefixing index and struct field vals// Exception is the only built-in state and mean a global error. All errors // have to [State.Require] the Exception state. If [Machine.PanicToErr] is // true, Exception will receive it. Exception string names S groups map[string][]int groupsOrder []string// prefix for nesting prefix string}var _ States = &StatesBase{}// Prefix returns the nesting prefix for this state definition.func ( *StatesBase) () string {return .prefix}func ( *StatesBase) () S {return .names}func ( *StatesBase) () (map[string][]int, []string) {return .groups, .groupsOrder}func ( *StatesBase) ( S) { .names = slicesUniq()}func ( *StatesBase) ( map[string][]int, []string) { .groups = .groupsOrder = }// States is the vase interface for schema states. TODO name to SchemaStates?typeStatesinterface {// Names returns the state names of the state machine.Names() SStateGroups() (map[string][]int, []string)SetNames(S)SetStateGroups(map[string][]int, []string)}// ///// ///// /////// ///// SCHEMA// ///// ///// /////// Schema is a map of state names to state definitions.typeSchemamap[string]State// Merge merges multiple state structs into one, overriding the previous// state definitions. No relation-level merging takes place.func ( Schema) ( ...Schema) Schema {// TODO mark all-but-last states as Inherited? // TODO example // TODO test // defaults := len()switch {case0:return } := .Clone()for := 0; < ; ++ {maps.Copy(, []) }// rm noname statesdelete(, "")return .Clone()}// Prefix will prefix all state names with [prefix]. skipPrefixed will skip// overlaps eg "FooFooName" will remain "FooName".func ( Schema) (string, bool, , S,) Schema { := Schema{}for , := range { = .Clone()iflen() > 0 && !slices.Contains(, ) {continue } elseiflen() > 0 && slices.Contains(, ) {continue }for , := range .After { := if ! || !strings.HasPrefix(, ) { = + } .After[] = }for , := range .Add { := if ! || !strings.HasPrefix(, ) { = + } .Add[] = }for , := range .Remove { := if ! || !strings.HasPrefix(, ) { = + } .Remove[] = }for , := range .Require { := if ! || !strings.HasPrefix(, ) { = + } .Require[] = } := if ! || !strings.HasPrefix(, ) { = + }// build [] = }return}// Clone deep clones the states struct and returns a copy.func ( Schema) () Schema { := make(Schema)for , := range { [] = .Clone() }return}// Parse sanitizes the schema and returns potential errors.func ( Schema) () (Schema, error) {// TODO capitalize states // TODO ErrFoo must require Exception := .Clone() := slices.Collect(maps.Keys())varerrorfor , := range {// avoid self removalifslices.Contains(.Remove, ) { .Remove = slicesWithout(.Remove, ) }// don't Remove if in Addfor , := range .Add {ifslices.Contains(.Remove, ) { .Remove = slicesWithout(.Remove, )// check if exists } elseif !slices.Contains(, ) { .Add = slicesWithout(.Add, ) } }// avoid being after itselfifslices.Contains(.After, ) { .After = slicesWithout(.After, ) }// detect require-remove conflictsfor , := range .Require {ifslices.Contains(.Remove, ) { = errors.Join(, errorf("%w: require-remove conflict for %s to %s",ErrSchema, , , )) } }// remove references to non-existing statesfor , := range .Remove {if !slices.Contains(, ) { .Remove = slicesWithout(.Remove, ) } }for , := range .After {if !slices.Contains(, ) { .After = slicesWithout(.After, ) } }for , := range .Remove {if !slices.Contains(, ) { .Remove = slicesWithout(.Remove, ) } } [] = }return , }// FilterByTag returns a subset schema with states having the given tag.func ( Schema) ( string) Schema { := Schema{}for , := range {ifslices.Contains(.Tags, ) { [] = } }return}// FilterByTagKey returns a subset schema with states having a value tag// prefixed with [key].func ( Schema) ( string) Schema { := Schema{}for , := range {for , := range .Tags {ifstrings.HasPrefix(, +":") { [] = break } } }return}// Names is a random-order list of defined state names.func ( Schema) () S {returnslices.Collect(maps.Keys())}func ( Schema) ( string) S {if , := []; ! {returnnil } := []returnslices.Concat(.Add, .After, .Require, .Remove)}func ( Schema) ( string, S) Schema { := Schema{}for , := range { := [] .Require = prefixRels(, , .Require) .Add = prefixRels(, , .Add) .Remove = prefixRels(, , .Remove) .After = prefixRels(, , .After) [+] = }return}// Get a map index with a default ret value.func ( Schema) ( string) State { , := []if ! {returnState{} }return}func ( Schema) ( Schema) bool {return .Names().HasN(.Names())}func ( Schema) ( S) bool {return .Names().HasN()}func prefixRels( string, , S) S {if == nil {returnnil } := make(S, len())for , := range {// prefix only the states from this schemaif !slices.Contains(, ) { [] = continue } [] = + }return}// ----- old// SchemaMerge is deprecated, use [Schema.Merge].func ( ...Schema) Schema { := len()switch {case0:returnSchema{}case1:return [0] } := make(Schema)for := 0; < ; ++ {// TODO clone?maps.Copy(, []) }return .Clone()}// StatesByTag is deprecated, use//// Schema.FilterByTag("").Names()func ( Schema, string) S { := S{}for , := range {for , := range .Tags {if == || strings.HasPrefix(, +":") { = append(, )break } } }return}// ///// ///// /////// ///// ARGS// ///// ///// /////constAPrefix = "_am"// ArgsApi is the base interface for typed arguments.typeArgsApiinterface {// ArgsPrefix returns the argument prefix inside the [A] map. Should be // provided by the implementation.ArgsPrefix() string// ArgsState represents the state this argument struct belongs to. // Defaults to [StateAny].ArgsState() string// TODO enable in v0.20 // ArgsPrefixNested returns both args prefix and the optional nesting prefix. // ArgsPrefixNested() string // TODO deep clone interface, optional // ArgsClone() G}// ArgsBase is the base implementation of [ArgsApi] interface.typeArgsBasestruct {ArgsApi// TODO enable in v0.20 // prefixNested string}// TODO enable in v0.20// func (a ArgsBase) Nest(nested string) ArgsBase {// a.prefixNested = nested// return a// }// TODO enable in v0.20// func (a ArgsBase) PrefixNested() string {// return a.ArgsState() + a.prefixNested// }// ArgsPrefix is a fallback to a stack trace hash of the implementation// symbol. Each pkg should overwrite this method.func ( ArgsBase) () string { := make([]byte, 4024) := runtime.Stack(, false) := string([:]) := strings.Split(, "\n")iflen() < 4 {// tinygo's runtime.Stack is a no-op, use a stable fallbackreturnHash("tinygo", 10) } := Hash([3], 10)return}// ArgsState is the default Any state.func ( ArgsBase) () string {returnStateAny}// Clone for deep cloning.func ( ArgsBase) () ArgsApi {// shallow clonereturn}// pkg args// Args for this pkg. Do not reuse.typeArgsstruct {ArgsBase}func (Args) () string {returnAPrefix}// -----// ExceptionArgsPanic is an optional argument ["panic"] for the StateException// state which describes a panic within a Transition handler.typeExceptionArgsPanicstruct { CalledStates S StatesBefore S Transition *Transition LastStep *Step StackTrace string}typeAExceptionstruct {Args Err error`log:"err"` ErrTrace string Panic *ExceptionArgsPanic// TODO handle Fn string`log:"fn"`// deadline TargetStates S CalledStates S TimeBefore Time TimeAfter Time Event *Event}func (AException) () string {returnStateException}// ACheck with a CheckDone chan which gets closed by the machine once it's// processed. Can cause chan leaks when misused. Only for Can* checks.typeACheckstruct {Args// TODO close these on dispose and deadline // TODO optimize: poll atomics instead of alloc chans (bench first) CheckDone chanstruct{}// Was the mutation canceled? Canceled bool}// -----// PassMerge merged one or more [A] into [A]. Technically a `map[string]any`// merge.func ( ...A) A { := A{}for , := range {for , := range { [] = } }return}// Pass accepts pointers of [ArgsBase] to pass to the machine as [A].func ( ...ArgsApi) A { := A{}for , := range { [ArgIndex()] = }return}// ParseArgs is [ParseArgsCheck] but without the check.func [ ArgsApi]( A) * { , := ParseArgsCheck[]()return}// ParseArgsCheck parses [A] into typed arguments described by the// passed generic// type. Returnsfunc [ ArgsApi]( A) (*, bool) {var := ArgIndex() , := [].(*)if ! {// RPC support , := [].()if ! {// fallbackreturn &, false } = & }return , true}// ArgIndex return an index of [arg] inside [A].func ( ArgsApi) string {// TODO arg.ArgsPrefixNested() := .ArgsPrefix() := .ArgsState()return + "__" + }// TODO// func (e *Event) ArgsState(state string, def any) any {// }
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.