runtime

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 35 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package runtime provides the SysML v2 execution runtime: expression evaluation, instance materialization, and KerML operator library.

Usage Example

// Create the model-derived part once, then a runtime context over it
model := runtime.NewModel(passes.NewTypedModel(resolver), resolver)
model.SetExpressionParser(parser.ParseOneExpression)
ctx := runtime.NewContext(model, runtime.DefaultMaxSteps)

// Instantiate a part
partSym := resolveSymbol(root, "MyCar")
inst, err := ctx.Instantiate(partSym)
if err != nil {
	log.Fatal(err)
}

// Evaluate an expression
exprNode := parseExpression("1 + 2")
result, err := ctx.Eval(exprNode)
if err != nil {
	log.Fatal(err)
}
fmt.Println(result.Const.Int) // 3

Architecture

The runtime is organized in three tiers:

  • Tier 1: Feature flattening (effective-feature lists per type)
  • Tier 2: Instance model (lazy feature value materialization, multiplicity-driven collections)
  • Tier 3: Expression evaluator (literals, operators, feature access, calc invocation, KerML builtins)

Key types:

  • Context: Runtime execution context (ID allocator, instance registry, memoization)
  • Value: Runtime-evaluable value (int/real/bool/string/null/instance/Sequence/Set)
  • EffectiveFeature: One entry in a type's effective feature list (Tier 1 schema)
  • Instance: Runtime-materialized object with typed feature values
  • EvalContext: Lexical environment for evaluation (frame stack)

Integration

  • Consumes semantics.Model (inherits features, multiplicity, constant folding)
  • Gates on pass-validated models (LevelConstraint success)
  • One Context per workspace session (LSP/REPL lifetime)

Behavioral simulation (actions, state machines) is out of scope (future Tiers 4–5).

Index

Constants

View Source
const (
	// DefaultMaxSteps bounds expression evaluations.
	DefaultMaxSteps int64 = 10000000
	// DefaultMaxActionSteps bounds the token-flow steps one action run performs.
	DefaultMaxActionSteps int64 = 1000000
	// DefaultMaxStateEvents bounds the events one state machine run dispatches.
	DefaultMaxStateEvents int64 = 1000000
	// DefaultMaxDoSteps bounds the do actions one state machine run
	// performs.
	DefaultMaxDoSteps int64 = 5000000
	// DefaultMaxElements bounds the collection elements one evaluation holds,
	// ~104MB of Values.
	DefaultMaxElements int64 = 1000000
	// DefaultMaxCalcDepth bounds the nested calc invocations one evaluation holds
	// on the stack, ~10KB each.
	DefaultMaxCalcDepth int64 = 10000
	// DefaultMaxSweepRuns bounds the runs one parameter sweep or sample makes,
	// each of which is a whole analysis or calc run of its own.
	DefaultMaxSweepRuns int64 = 1000
	// DefaultMaxIntegerBits bounds the magnitude of one Integer a run computes,
	// 2^20 bits (315,653 decimal digits, 128KiB).
	DefaultMaxIntegerBits = semantics.DefaultMaxIntegerBits
)

Default bounds on one run. Each one stops a different kind of runaway, so each counts a different thing and has its own variable.

The step and event bounds are sized by how long a runaway takes to report rather than by memory: those steps allocate nothing that outlives them, and the only thing they make grow is a %trace, at 34-83 bytes an entry. Measured rates are ~13.6M evaluation steps/s and ~1.9M events/s, so each default reports a runaway within about a second, and a fully traced run at those four ceilings holds ~320MB.

Collection elements are the exception, and MaxElements is the bound that reads as memory: a materialized element is a 104-byte Value living as long as the collection holding it, and `1..10000000` conjures one per step. It counts the elements one evaluation holds, not the elements a run produced in total, so a loop or a state machine building a small collection each step is not stopped by the steps before it.

View Source
const (
	MaxStepsEnvVar       = "OPENSYSML_MAX_STEPS"
	MaxActionStepsEnvVar = "OPENSYSML_MAX_ACTION_STEPS"
	MaxStateEventsEnvVar = "OPENSYSML_MAX_EVENTS"
	MaxDoStepsEnvVar     = "OPENSYSML_MAX_DO_STEPS"
	MaxElementsEnvVar    = "OPENSYSML_MAX_ELEMENTS"
	MaxCalcDepthEnvVar   = "OPENSYSML_MAX_CALC_DEPTH"
	MaxSweepRunsEnvVar   = "OPENSYSML_MAX_SWEEP_RUNS"
	MaxIntegerBitsEnvVar = "OPENSYSML_MAX_INTEGER_BITS"
)

Environment variables overriding the defaults above, following the OPENSYSML_LIBRARY_PATH convention. The legacy SYSML_-prefixed names remain accepted via envvar.Lookup, with the OPENSYSML_ name winning when both are set.

View Source
const (
	BoundSteps       = "steps"
	BoundActionSteps = "actionSteps"
	BoundEvents      = "events"
	BoundDoSteps     = "doSteps"
	BoundElements    = "elements"
	BoundBehaviors   = "behaviors"
)

The executor budgets a search runs under, by the name a bound hit reports; each names one field of Budgets, so a report spells the limit that stopped it.

View Source
const (
	MonteCarloRunsOutput      = "runs"
	MonteCarloMeanOutput      = "mean"
	MonteCarloDeviationOutput = "deviation"
	MonteCarloOutOfSpecOutput = "outOfSpec"
)

The features Simulation::MonteCarlo declares, by the name each is declared under; the outputs are exported for the comparison of a case's statistics with a tool's.

View Source
const CalcCompileEnvVar = "OPENSYSML_CALC_COMPILE"

CalcCompileEnvVar switches the compiled tier for pure calc bodies off when set to 0 (or false/off/no), leaving every calc to the reference evaluator.

View Source
const ChoiceDiagnosticCode = "choice-point"

ChoiceDiagnosticCode is the code every choice-point diagnostic carries.

View Source
const HeldObjectDepth = maxMaterializeDepth

HeldObjectDepth is how many objects deep validating an object reaches: a feature held deeper is cut, as materializing it would be.

View Source
const MinMaxIntegerBits = semantics.MinMaxIntegerBits

MinMaxIntegerBits is the least Integer size budget a run may be given.

View Source
const ScheduleEnd = -1

ScheduleEnd asks ReplaySchedule for the run's end, every move followed.

View Source
const ToolDivergenceCode = "tool-divergence"

ToolDivergenceCode is the diagnostic code of a ToolDivergence note.

View Source
const UndeterminedText = "<undetermined>"

UndeterminedText is how every surface spells a result the model does not determine: a model-level read of a valueless or open-count feature, or over one.

View Source
const UnevaluableGuardCode = "guard-unevaluable"

UnevaluableGuardCode is the code a diagnostic about a guard the run could not evaluate carries.

View Source
const UnsetText = "<unset>"

UnsetText is how every surface spells a feature value that holds no value: a valueless feature of a value type, whose instances are values rather than objects.

Variables

View Source
var (

	// ErrStepLimitExceeded is returned when the evaluation step counter exceeds maxSteps.
	ErrStepLimitExceeded = errors.New("evaluation step limit exceeded")

	// ErrInterrupted is returned when a run is stopped from outside, through the
	// flag Context.SetInterrupt installs, before it ended on its own.
	ErrInterrupted = errors.New("interrupted")

	// ErrElementLimitExceeded is returned when the collection elements one run
	// materializes exceed maxElements. It is a bound on memory rather than on
	// work, so it is its own error and its own budget.
	ErrElementLimitExceeded = errors.New("collection element limit exceeded")

	// ErrIntegerSizeLimit is returned when an Integer result would need more
	// bits than the run's Integer size budget allows. Integers are unbounded;
	// the budget bounds the memory and time one result may take.
	ErrIntegerSizeLimit = semantics.ErrIntegerSizeLimit

	// ErrInstanceLimitExceeded is returned when materializing one more object
	// would take the context past the bound SetMaxInstances set.
	ErrInstanceLimitExceeded = errors.New("object limit exceeded")

	// ErrUnresolvedReference is returned when a feature reference cannot be resolved.
	ErrUnresolvedReference = errors.New("unresolved reference")

	// ErrTypeMismatch is returned when an operation receives a value of unexpected type.
	ErrTypeMismatch = errors.New("type mismatch")

	// ErrDivisionByZero is returned when a division or remainder has a zero
	// divisor. It is the answer to the expression, not a missing declaration.
	ErrDivisionByZero = semantics.ErrDivisionByZero

	// ErrMultiplicityViolation is returned when a feature value access/assignment violates multiplicity bounds.
	ErrMultiplicityViolation = errors.New("multiplicity violation")

	// ErrUniquenessViolation is returned when a value written to a unique feature repeats one of its values.
	ErrUniquenessViolation = errors.New("uniqueness violation")

	// ErrNotACalc is returned when a calc invocation targets a symbol that is
	// not a calc definition or usage.
	ErrNotACalc = errors.New("not a calc")

	// ErrNotAConstraint is returned when a symbol asked to be evaluated as a
	// constraint declares something else. It is a usage error about the request,
	// not a verdict about the model, so callers can tell the two apart.
	ErrNotAConstraint = errors.New("not a constraint")

	// ErrNotARequirement is returned when a symbol asked to be evaluated as a
	// requirement declares something else. Like ErrNotAConstraint it reports the
	// request, not the model.
	ErrNotARequirement = errors.New("not a requirement")

	// ErrNotAnObject is returned when a symbol asked to be validated as an object
	// has no objects: a package, an attribute, a comment. It reports the request.
	ErrNotAnObject = errors.New("not an object")

	// ErrNotAnAnalysis is returned when a symbol asked for its objectives or
	// asked to be run is not a case whose body runs. Like ErrNotAConstraint it
	// reports the request, not the model.
	ErrNotAnAnalysis = errors.New("not an analysis case")

	// ErrAcceptDeadlock is returned when an action can no longer progress
	// because every token it has left is parked at an accept, so no token can
	// post the message any of them waits for. An accept suspends the action
	// rather than failing, so this is how a suspension that can never end is
	// reported instead of hanging.
	ErrAcceptDeadlock = errors.New("accept deadlock")

	// ErrActionDeadlock is returned when action tokens cannot make progress.
	ErrActionDeadlock = errors.New("action deadlock")

	// ErrExecutorReleased is returned when a released executor is stepped.
	ErrExecutorReleased = errors.New("executor released")

	// ErrNegativeDuration is returned when a delay — an `accept after`, a time
	// transition's or an advance of the clock — is negative, infinite, no number
	// at all, or leads past the last instant the clock can hold: the clock never
	// runs backwards and always reads a finite instant.
	ErrNegativeDuration = errors.New("negative duration")

	// ErrNothingDue is returned when one step is asked of an executor whose only
	// remaining work waits on the clock for an instant it has not reached.
	ErrNothingDue = errors.New("nothing due at the current instant")

	// ErrCalcRecursionLimit is returned when calc invocation nests deeper than
	// the run's calc depth budget, which an unbounded recursion would otherwise
	// do until the process ran out of stack.
	ErrCalcRecursionLimit = errors.New("calc recursion limit exceeded")

	// ErrActionStepLimitExceeded is returned when an action executor exceeds
	// its token-flow step budget.
	ErrActionStepLimitExceeded = errors.New("action step limit exceeded")

	// ErrStateEventLimitExceeded is returned when state processing exceeds its
	// event budget.
	ErrStateEventLimitExceeded = errors.New("state event limit exceeded")

	// ErrDoStepLimitExceeded is returned when a state do behavior exceeds its
	// action-step budget.
	ErrDoStepLimitExceeded = errors.New("state do-step limit exceeded")

	// ErrMixedArguments is returned when an operation invocation gives positional and
	// named arguments together: an argument list is one form or the other (KerML 8.2.5.8.3).
	ErrMixedArguments = errors.New("positional and named arguments mixed")

	// ErrStreamCycle is returned when streaming flows lead a value written to a pin back
	// to that pin while the write is still being carried on.
	ErrStreamCycle = errors.New("streaming flows form a cycle")

	// ErrViolated is returned when an asserted constraint or a required
	// condition evaluates to false. It is a verdict about the model, not a
	// failure to evaluate, so callers can tell the two apart.
	ErrViolated = errors.New("evaluated to false")

	// ErrNoValue is returned when a feature a condition names carries no value:
	// neither a feature value on the object being checked nor a declared default.
	ErrNoValue = errors.New("no value")

	// ErrNoConditions is returned when a constraint or requirement carries no
	// condition to evaluate: reporting a verdict would claim a check that never ran.
	ErrNoConditions = errors.New("no condition to evaluate")

	// ErrCyclicFeatureValue is returned when a feature value's default value depends, directly or
	// through other feature values, on the one being computed.
	ErrCyclicFeatureValue = errors.New("cyclic feature value dependency")

	// ErrIncommensurableUnits is returned when an operation combines quantities
	// whose units measure different things; see semantics.ErrIncommensurableUnits.
	ErrIncommensurableUnits = semantics.ErrIncommensurableUnits

	// ErrNotASatisfaction is returned when a satisfaction assertion is asked of
	// an element that states none.
	ErrNotASatisfaction = errors.New("not a satisfaction assertion")

	// ErrNoRequirement is returned when a satisfaction assertion states no
	// requirement to evaluate: it references none, or references one that
	// resolves to nothing.
	ErrNoRequirement = errors.New("no requirement to satisfy")

	// ErrIndexOutOfRange is returned when an index names no position of the
	// sequence or string it indexes; indices are 1-based, so 0 is out of range
	// as much as size+1 is, and each operation names what it indexed.
	ErrIndexOutOfRange = errors.New("index out of range")

	// ErrBodyArity is returned when the body expression a collection operation
	// is given declares a number of parameters the operation cannot call it
	// with: `select` calls its selector with one element, so a selector
	// declaring two parameters has no second argument to receive.
	ErrBodyArity = errors.New("body parameter count mismatch")

	// ErrVariationUnselected is returned when a variation is read without having
	// been bound to one of its variants: it classifies its variants abstractly,
	// so it stands for no one value until a variant is selected.
	ErrVariationUnselected = errors.New("variation has no variant selected")

	// ErrFeatureValueMaterialization marks an error as a feature value that could not be
	// materialized, whatever kept it from materializing. Reading a feature value is what
	// finds such a failure, so a surface reporting one answered nothing about
	// that feature value rather than deciding anything about the model.
	ErrFeatureValueMaterialization = errors.New("feature value could not be materialized")

	// ErrNoSuchFeature is returned when a member read, a write, or a chained
	// assignment reaches an object whose type declares no feature of that name:
	// the object has nothing to answer with and nowhere to hold the value.
	ErrNoSuchFeature = errors.New("object has no such feature")

	// ErrNeedsObject is returned when a case a definition owns is run with no
	// object of the definition to run on: the case is a feature of such an
	// object, so with none instantiated its body has nothing to read.
	ErrNeedsObject = errors.New("needs an object")
)
View Source
var DefaultExploreBudget = ExploreBudget{Runs: 1024, Depth: 64}

DefaultExploreBudget is the budget `explore` has when its spelling names none.

View Source
var DefaultExploreSchedulePolicy = SchedulePolicy{/* contains filtered or unexported fields */}

DefaultExploreSchedulePolicy is `explore` with no options: every linearization within the default budget.

View Source
var DefaultSchedulePolicy = SchedulePolicy{/* contains filtered or unexported fields */}

DefaultSchedulePolicy is the policy runs use unless one is set: `reverse`.

View Source
var ErrAmbiguousSubject = errors.New("ambiguous subject")

ErrAmbiguousSubject is returned when more than one object carries the checked element, so which one the verdict would be about is a question, not an answer.

View Source
var ErrCheckRefused = errors.New("check refused")

ErrCheckRefused is the typed error every move the run could not make as the checker selected it wraps.

View Source
var ErrClockStep = errors.New("invalid clock step")

ErrClockStep is the typed error a clock step that is not a finite, non-negative number is refused with.

View Source
var ErrExplorationDiverged = errors.New("exploration diverged")

ErrExplorationDiverged is the typed error for a replay that did not meet the choice points its prefix recorded, so no outcome set can be trusted.

View Source
var ErrExploreUndriven = errors.New("explore is not a policy one context runs under")

ErrExploreUndriven is the typed error SetSchedule returns for `explore`, which Explore drives over fresh contexts rather than one.

View Source
var ErrInvalidSchedulePolicy = errors.New("invalid scheduling policy")

ErrInvalidSchedulePolicy is the typed error every unparseable policy spelling wraps.

View Source
var ErrNoMetaclass = errors.New("no reflective metaclass classifies the element")

ErrNoMetaclass is returned when an element's declaration is classified by no reflective metaclass the loaded libraries declare, so it has no metaobject.

View Source
var ErrNotCarried = errors.New("object does not carry the case")

ErrNotCarried is returned when a case a type owns is run on an object that is not of that type and holds none.

View Source
var ErrNotExploring = errors.New("scheduling policy does not explore")

ErrNotExploring is the typed error Explore returns for a policy that is not `explore`.

View Source
var ErrReflectiveFeatureUnsupported = errors.New("reflective feature is not derived")

ErrReflectiveFeatureUnsupported is returned when a metaclass declares the feature read from a metaobject but the runtime derives no value for it.

View Source
var ErrReplayDisagrees = errors.New("replay disagrees with the witness")

ErrReplayDisagrees is the typed error every replay that reaches another state wraps.

View Source
var ErrReplayRefused = errors.New("replay refused")

ErrReplayRefused is the typed error every refused replay move wraps.

View Source
var ErrRescheduleMidRun = errors.New("reschedule inside a step")

ErrRescheduleMidRun is Reschedule from inside a step.

View Source
var ErrSnapshotMidRun = errors.New("snapshot inside a step")

ErrSnapshotMidRun reports a snapshot asked for from inside a step: a snapshot is taken between steps, where no run, body or evaluation is on the stack.

View Source
var ErrSnapshotPausedBody = errors.New("snapshot of a body paused mid-statement")

ErrSnapshotPausedBody reports a body paused mid-statement — a token's step a breakpoint or a wait on the clock suspended, or a do behavior waiting — whose continuation points into its model's lowered statements: a Snapshot of the same context captures it, a portable image (HeldImage) does not.

View Source
var ErrTool = errors.New("tool failed")

ErrTool is the typed error every failure of a tool invocation unwraps to.

View Source
var ErrToolDryRun = errors.New("tool dry run")

ErrToolDryRun is the error a dry run stops the performance with at its first tool call; it passes through unchanged.

View Source
var ErrUnknownCheckFeature = errors.New("no such feature to check divergence of")

ErrUnknownCheckFeature is the typed error a check whose Diverge names no feature wraps.

View Source
var ErrUnseededDraw = errors.New("modeled randomness needs a seed")

ErrUnseededDraw is the typed error a modeled draw raises when no seed fixes it.

View Source
var ErrWitnessInput = errors.New("witness input refused")

ErrWitnessInput is the typed error every witness input the run cannot fix wraps.

ExecutorBounds lists the executor budgets a bound hit may name, in report order.

View Source
var SchedulePolicyNames = []string{"declared", "reverse", "seed:<n>", "explore[:runs=<n>,depth=<d>]", "replay:<file>"}

SchedulePolicyNames lists the policy spellings ParseSchedulePolicy accepts, for usage text; `seed:<n>` stands for any non-negative decimal seed and the bracketed options of `explore` are each optional; `replay:<file>` names a file of choice lines.

SignalDefinitionKinds are the definitions a signal is declared as: what an accept may be typed by and a send may carry. A behavior definition is neither.

Functions

func ActionNodeName

func ActionNodeName(node ast.Node) string

ActionNodeName returns the declared name of an action graph node, or "" when the node is anonymous or not a named node kind.

func BranchLabel

func BranchLabel(pos int, target ast.Node) string

BranchLabel names a decision's succession as a choice line does: its declared position, counted from 1, and its target.

func CheckClockStep

func CheckClockStep(step float64) error

CheckClockStep is ErrClockStep unless step is a finite, non-negative number of seconds.

func ConditionText added in v0.10.0

func ConditionText(n ast.Node) string

ConditionText is the text a NoValueError names the expression n by.

func DecisionPlace

func DecisionPlace(node ast.Node) string

DecisionPlace is where a choice line places a decision node's branch choice.

func DeclScope

func DeclScope(sym *symbols.Symbol) *symbols.Scope

DeclScope returns the scope a declaration's body was written in: the scope the declaration owns, in which its own members are visible to each other, falling back to the scope it was declared in when it owns none. It is the scope an expression written among its members resolves its names against — an attribute default, a guard, an assignment in a nested action body — and the scope the runtime lowers the declaration in.

func DescribeGaps added in v0.11.0

func DescribeGaps(gaps []CoverageGap) string

DescribeGaps joins the gaps' descriptions, in their order.

func DescribeValue added in v0.11.0

func DescribeValue(val Value) string

DescribeValue names a value's kind for a diagnostic, distinguishing the numeric constants a single kind covers.

func ElementCount added in v0.10.0

func ElementCount(val Value) int64

ElementCount is how many values val holds: a collection's elements, required members counted made or not; none for null; one for any other value.

func ExecutorBound

func ExecutorBound(name string, b Budgets) (int64, bool)

ExecutorBound is the limit the named executor bound has under the budgets, false for a name that is no executor bound's. The object behaviors' rounds are counted in events, so both names spell the events limit.

func FormatChoices

func FormatChoices(choices []ChoiceTaken) string

FormatChoices renders a witness as one line, its choices in run order.

func FormatComplex

func FormatComplex(z complex128) string

FormatComplex renders a complex number as its parts read, `1.0 + 2.0i`, with the imaginary part's sign as the operator: `1.0 - 2.0i`.

func FormatTraceValue

func FormatTraceValue(v Value) string

FormatTraceValue renders a runtime value canonically for a trace. Set elements are sorted by their rendering, since a set has no order of its own and its backing map does not iterate in a stable one.

func FormatValue

func FormatValue(v Value) string

FormatValue renders a value with the notation used by user-facing runtime results and diagnostics.

func FormatWeight

func FormatWeight(w float64) string

FormatWeight spells a weight as a trace reports it.

func GapNames added in v0.11.0

func GapNames(gaps []CoverageGap) []string

GapNames lists the gaps' identifiers, in their order.

func IsRunnableCaseSymbol

func IsRunnableCaseSymbol(sym *symbols.Symbol) bool

IsRunnableCaseSymbol reports whether sym declares a case whose body runs as steps: an analysis case or a verification case, definition or usage.

func IsSignalDefinition

func IsSignalDefinition(sym *symbols.Symbol) bool

IsSignalDefinition reports whether a symbol declares a definition a signal may be typed by, one of SignalDefinitionKinds.

func IsUninitializedFeatureValue added in v0.11.0

func IsUninitializedFeatureValue(err error) bool

IsUninitializedFeatureValue reports whether err is a read of a required feature that holds no value and has no default, which a caller shows as unset rather than as a failure.

func IsVerificationCaseSymbol

func IsVerificationCaseSymbol(sym *symbols.Symbol) bool

IsVerificationCaseSymbol reports whether sym declares a verification case definition or usage.

func LibraryFunctionParams

func LibraryFunctionParams(fqn string) (params []string, ok bool)

LibraryFunctionParams is the declared parameter names of the library function fqn in declared order, an anonymous parameter as "".

func Magnitude

func Magnitude(value Value) (semantics.Value, string, bool)

Magnitude is MagnitudeValue with the quantity's unit ("" for a bare number); a one-element sequence is read as its element, so its unit is the element's.

func MagnitudeValue

func MagnitudeValue(value Value) (semantics.Value, bool)

MagnitudeValue is the number a value is as written, Integer or Real, a quantity's magnitude included, and whether it is one.

func NegatedDecl

func NegatedDecl(sym *symbols.Symbol) bool

NegatedDecl reports whether sym's declaration asserts that its conditions do not hold (`assert not constraint { … }`, `assert not satisfy … by …`).

func OrderDependenceText added in v0.11.0

func OrderDependenceText(unresolved int) string

OrderDependenceText is the marker a value nothing fixed prints with: how many of the run's unresolved choice points touch it, and where the set it stands in is shown. Empty for a value no conflicting alternative wrote.

func ParseClockStep

func ParseClockStep(text string) (float64, error)

ParseClockStep reads a clock step as `-clock-step` and a witness spell it: a finite, non-negative number of seconds, else ErrClockStep.

func PooledDeviation

func PooledDeviation(mean float64, spreads []Spread, dof int) float64

PooledDeviation is the root of the weighted squares of spreads, those About the mean taken from it, over dof degrees of freedom, 0 for none. Values and mean are scaled by the power of two below the largest before differencing and squaring, which rounds nothing, so finite values however large or far apart pool to a finite deviation.

func ReplaySpelling

func ReplaySpelling(spelling string) bool

ReplaySpelling reports whether the spelling asks for a replay, whose file ParseSchedulePolicy reads; a surface with no files of the caller's refuses it before parsing.

func RequireAnalysis

func RequireAnalysis(sym *symbols.Symbol) error

RequireAnalysis returns an ErrNotAnAnalysis usage error unless sym declares an analysis case, so a caller can settle the kind before asking for objectives.

func RequireConstraint

func RequireConstraint(sym *symbols.Symbol) error

RequireConstraint returns an ErrNotAConstraint usage error unless sym declares a constraint, so a caller can settle the kind before evaluating.

func RequireObject

func RequireObject(sym *symbols.Symbol) error

RequireObject is ErrNotAnObject unless sym has objects to validate: a definition or usage that is neither a namespace nor a data value (attribute, enumeration).

func RequireRequirement

func RequireRequirement(sym *symbols.Symbol) error

RequireRequirement returns an ErrNotARequirement usage error unless sym declares a requirement.

func RequirementVerdicts added in v0.10.0

func RequirementVerdicts(v RequirementVerifier, scopes []*symbols.Scope) view.Verdicts

RequirementVerdicts is the verdict overlay v answers over the cases in scopes: each case verifying a requirement, the subcases its body performs aside.

func ResolveCheckFeatures

func ResolveCheckFeatures(exec *ActionExecutor, names []string) (map[string]FeatureOwner, error)

ResolveCheckFeatures resolves the names a check compares as Check does over an invocation of the started action exec alone, telling whose feature each is; a name nothing answers to is an unknownCheckFeatureError.

func RunSeed

func RunSeed(seed uint64, i int64) uint64

RunSeed is the model seed run i (from 1) of a Monte Carlo seeded from seed draws under: SplitMix64's finalizer over seed + i·stride, a bijection, so two runs of one Monte Carlo never share a seed, and run i is the same on every platform.

func SettleMonteCarloRuns added in v0.9.2

func SettleMonteCarloRuns(runs []*MonteCarloRun, stats *MonteCarloStatistics) ([]bool, error)

SettleMonteCarloRuns settles every run's checks over the sample's statistics and counts outOfSpec into stats, returning the checks that are the sample's. The point between it and the last run's Conclude is where a call boundary before the conclusion is taken.

func StateVertexName

func StateVertexName(node ast.Node) string

StateVertexName returns the name of a StateNode or PseudostateNode, "" for any other node.

func SymbolText added in v0.11.0

func SymbolText(sym *symbols.Symbol) string

SymbolText names a symbol in diagnostics, falling back to its kind when it is anonymous.

func TokenLabel

func TokenLabel(id int64, node ast.Node) string

TokenLabel names a token as a choice line does: its ID at the node it sits at.

func WeightedMean

func WeightedMean(weighted []Counted) (mean float64, count int64)

WeightedMean is the mean of the values weighted by their counts, exact until it rounds to a Real, with the exact total count; a value that is no finite number carries into the mean as Real arithmetic would carry it.

Types

type AcceptWait

type AcceptWait struct {
	ParamName  string // the accept parameter the message will bind to
	SignalType string // the type awaited, empty when the accept named none
	ViaPort    string // the port awaited on, empty when the accept named none
	Since      int    // the step during which the token parked, numbered as the trace numbers steps
	// Trigger describes the time or change event awaited instead of a message
	// (`accept when x > 1`), empty when the accept waits for a message.
	Trigger string
	// Timed is set for a wait on the context's clock, Due the instant it ends.
	Timed bool
	Due   float64
}

AcceptWait describes the message a parked token is waiting for. It is the accept's lowered shape plus the step the token parked at, which is what lets a blocked run report which accept is waiting for what rather than only that it is stuck.

func (AcceptWait) String

func (w AcceptWait) String() string

String describes what a parked token is waiting for, and since when, for error messages and for the REPL's view of a suspended executor.

type ActionExecutor

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

ActionExecutor executes action bodies using token-flow semantics.

func (*ActionExecutor) AcceptTaking

func (e *ActionExecutor) AcceptTaking(m Message) (taking []TakingAccept, err error)

AcceptTaking lists the accepts parked for m, in the action's own flow and in the work it performs, in the order their tokens are held; the step dispatching m lets one go on.

func (*ActionExecutor) AcceptsMessage

func (e *ActionExecutor) AcceptsMessage(m Message) (accepted bool, err error)

AcceptsMessage reports whether a token parked at a signal accept, or an action performed for a paused token, would take m; a port failing to resolve is the error.

func (*ActionExecutor) ActionSymbol

func (e *ActionExecutor) ActionSymbol() *symbols.Symbol

ActionSymbol returns the action being executed.

func (*ActionExecutor) Awaiting

func (e *ActionExecutor) Awaiting(token Token) []lower.ActionEdge

Awaiting returns the successions into the node token is held at that no token has arrived over yet, nil for a token not held there.

func (*ActionExecutor) Breakpoints added in v0.11.0

func (e *ActionExecutor) Breakpoints() []string

Breakpoints lists the node names breakpoints are set at, sorted.

func (*ActionExecutor) ClearBreakpoints

func (e *ActionExecutor) ClearBreakpoints()

ClearBreakpoints removes all breakpoints.

func (*ActionExecutor) Data

func (e *ActionExecutor) Data() map[string]Value

Data returns the live feature space of the action's own performance; a nested node's features live in its own performance and are reported by Results.

func (*ActionExecutor) Graph

func (e *ActionExecutor) Graph() *lower.ActionGraph

Graph is the lowered flow the run performs, the one every step of it consumes.

func (*ActionExecutor) HasPendingSignal

func (e *ActionExecutor) HasPendingSignal() bool

HasPendingSignal reports whether a message in flight would let a parked token proceed, without consuming it.

func (*ActionExecutor) Held

func (e *ActionExecutor) Held() Held

Held copies what the action's own performance holds now.

func (*ActionExecutor) Holds

func (e *ActionExecutor) Holds(sym *symbols.Symbol, scope *symbols.Scope) (bool, error)

Holds evaluates a requirement or constraint against the run's state as the executor now holds it: a feature the condition names resolves to the performance's value first, then to the performer's, then to the declaration. It reports whether the conditions hold as CheckRequirementOn and CheckConstraintOn decide, the condition that failed carried as a ViolationError, and a runtime failure of the evaluation as its own error.

func (*ActionExecutor) KeepTraversals

func (e *ActionExecutor) KeepTraversals(keep bool)

KeepTraversals has the run keep the successions its tokens take until TraversalsSince releases them, for a debugger; off (the default), it keeps none.

func (*ActionExecutor) NextWait

func (e *ActionExecutor) NextWait() (float64, bool)

NextWait returns the instant the earliest token parked on the clock proceeds at, false when none is; one already due is not a wait.

func (*ActionExecutor) NodeNames

func (e *ActionExecutor) NodeNames() []string

NodeNames returns the names of the action's graph nodes, in declaration order, then those of the flows nested under it: the flows its nodes own and the block flows their bodies state. Anonymous nodes are omitted; a debugger uses it to check that a breakpoint names a node that exists.

func (*ActionExecutor) NoteCount

func (e *ActionExecutor) NoteCount() int

NoteCount is how many notes the executor's run has made so far.

func (*ActionExecutor) Notes

func (e *ActionExecutor) Notes() []RunNote

Notes returns what the executor's run noted so far, in order; see Context.Notes.

func (*ActionExecutor) NotesSince

func (e *ActionExecutor) NotesSince(mark int) []RunNote

NotesSince returns what the executor's run noted since mark, a NoteCount read earlier.

func (*ActionExecutor) Outcome

func (e *ActionExecutor) Outcome() Outcome

Outcome is the outcome of the run so far: the values its features hold, and whether a `terminate` ended it short of its own end.

func (*ActionExecutor) PausedAt

func (e *ActionExecutor) PausedAt() string

PausedAt returns the breakpoint node the last run stopped at, or "" when the run was not stopped by a breakpoint.

func (*ActionExecutor) PausedBreakpoint

func (e *ActionExecutor) PausedBreakpoint() (NodeBreakpoint, bool)

PausedBreakpoint identifies the node the last run stopped at, in its nested flow: a node a body performs is identified even as its token stays on the enclosing action. False when the run was not stopped by a breakpoint. The path is the caller's own.

func (*ActionExecutor) Performer

func (e *ActionExecutor) Performer() *Instance

Performer returns the object performing the action, nil for an action performed outside any object.

func (*ActionExecutor) PerformerAttributes

func (e *ActionExecutor) PerformerAttributes() []string

PerformerAttributes names, in name order, the attributes of the object performing the action: the features a check compares for it absent names; none without one.

func (*ActionExecutor) Release

func (e *ActionExecutor) Release()

Release ends the run for good: the work of every token a breakpoint left paused is ended, so an executor abandoned mid-run holds no suspended run, the clock drives it no further, and a later Step or RunToCompletion returns ErrExecutorReleased, completed or not. Safe to call more than once.

func (*ActionExecutor) ReplaceBreakpointsAt

func (e *ActionExecutor) ReplaceBreakpointsAt(bps []NodeBreakpoint)

ReplaceBreakpointsAt makes bps the breakpoints set by identity, named or not, one occurrence of a node each: a debugger holding the graph (Graph, Token.Within) sets breakpoints this way. A stop already made at one kept stands, so a resumed run passes it; one removed stops again once re-set.

func (*ActionExecutor) Results

func (e *ActionExecutor) Results() map[string]Value

Results returns the values the action's features hold, under `node.pin` those of each nested non-repeated node's latest performance and under `part.attribute` what the one object each of its own parts denotes holds; a performed usage's mirror its occurrence.

func (*ActionExecutor) ResultsWithError added in v0.10.0

func (e *ActionExecutor) ResultsWithError() (map[string]Value, error)

ResultsWithError returns the values the action's features hold and the first binding derivation error; a feature whose binding fails to derive is omitted.

func (*ActionExecutor) Resume

func (e *ActionExecutor) Resume() bool

Resume returns a run a breakpoint suspended to running, for a driver that moves it by other means than a step: the clock, say. Any other state is left as it is.

func (*ActionExecutor) RunToCompletion

func (e *ActionExecutor) RunToCompletion() error

RunToCompletion executes until StateCompleted, a breakpoint, or error. Includes infinite loop protection.

A run stops as soon as a token sits on a node a breakpoint was set on (see SetBreakpoint), or a body a token runs is about to perform one, leaving the tokens where they are so the run can be resumed by calling RunToCompletion again or stepped with Step; PausedAt names the node it stopped at. With no breakpoints set the run is unconditional.

A message-parked action can be resumed by its caller posting a matching message after this run returns; an unowned run reports ErrAcceptDeadlock when none can. A token parked on the clock is resumed by advancing it to its instant.

func (*ActionExecutor) RunToQuiescence

func (e *ActionExecutor) RunToQuiescence() error

RunToQuiescence runs the action until it completes, stops at a breakpoint, or parks every remaining token at an accept, holding the clock where it is: for an object's action a parked token is quiescence, not a deadlock.

func (*ActionExecutor) SetBreakpoint

func (e *ActionExecutor) SetBreakpoint(nodeName string)

SetBreakpoint adds a breakpoint at the given node name.

func (*ActionExecutor) SetInputs

func (e *ActionExecutor) SetInputs(inputs map[string]Value)

SetInputs binds input parameter values into the action's feature space. Inputs are applied after attribute defaults, so they override defaults with the same name. Must be called before initialize().

func (*ActionExecutor) SetTrace

func (e *ActionExecutor) SetTrace(trace *TraceRecorder)

SetTrace sets the trace recorder for this executor and the context it evaluates in.

func (*ActionExecutor) State

func (e *ActionExecutor) State() ExecutionState

State returns current execution state.

func (*ActionExecutor) Step

func (e *ActionExecutor) Step() error

Step advances execution by one step for all active tokens. Safely handles token slice modifications (fork/join) by collecting indices first.

A step moves each token at most once: a token the step created or moved — a fork's branch, the one a synchronized node performs with — has its first step in the next, so the tokens held at a node are all in before it performs.

A token that reaches an accept with no message it can consume parks there rather than failing: the action is suspended until a matching message arrives. When a step moves nothing and at least one token is parked, the executor enters StateWaiting instead of reporting a deadlock — a caller driving Step itself (the REPL, or a state machine running in the same context) may still post the awaited message and step again, which resumes the parked token. RunToCompletion has no such caller, so it turns a step that leaves the executor waiting into ErrAcceptDeadlock.

A step ends early, with the executor suspended, when a body a token runs is about to perform a node a breakpoint is set on (see SetBreakpoint): the token stays at its node with its work half done and no further token steps. The next step steps the other tokens first, then resumes it.

Returns an error if a deadlock unrelated to accepts is detected (no progress made and nothing is waiting for a message).

func (*ActionExecutor) StepToBreakpoint

func (e *ActionExecutor) StepToBreakpoint() error

StepToBreakpoint is Step with the breakpoints a run stops at: a token sitting on one the run has not yet stopped at suspends the run before any token moves, and one a step lands on suspends it after, so the next step resumes past it.

func (*ActionExecutor) Tokens

func (e *ActionExecutor) Tokens() []Token

Tokens returns a copy of active tokens.

func (*ActionExecutor) TraversalCount

func (e *ActionExecutor) TraversalCount() int

TraversalCount counts the successions taken so far, released ones included: a mark to read what a later step took from.

func (*ActionExecutor) Traversals

func (e *ActionExecutor) Traversals() []Traversal

Traversals returns the successions kept, in order: a fork's branches as the tokens they spawned, a join as the one token that passes on.

func (*ActionExecutor) TraversalsSince

func (e *ActionExecutor) TraversalsSince(mark int) []Traversal

TraversalsSince returns the kept successions taken since mark, a TraversalCount read earlier, and releases those before it: the run keeps only from the last mark.

type AdvanceReport

type AdvanceReport struct {
	// From and To are the instants the clock moved between, in seconds.
	From, To float64
	// Events, DoSteps and Steps count the state events dispatched, the do
	// actions run and the action steps taken along the way.
	Events, DoSteps, Steps int64
	// Dropped are the signals dispatched along the way that no transition
	// consumed and no do behavior went on with: deferred by the active state, or dropped.
	Dropped []Dispatch
	// Notes are what the advance noted: the choice points it drew and the
	// guards it could not evaluate, in order.
	Notes []RunNote
}

AdvanceReport is what one advance of the clock did.

type AffineTransformation3d

type AffineTransformation3d struct {
	Rotation    [9]float64
	Translation [3]float64
}

AffineTransformation3d is an AffineTransformationMatrix3d: the 3x3 rotation in row-major order and the translation, both bare numbers.

type AnalysisArgs

type AnalysisArgs struct {
	// Subject is the object the case is run on; nil leaves the case's own
	// subject binding, or the enclosing case's subject, to supply it.
	Subject *Instance

	// Positional bind the input parameters the case does not bind itself, in
	// declaration order; the subject is never among them.
	Positional []Value

	// Named bind parameters by name.
	Named map[string]Value
}

AnalysisArgs are the values a run of an analysis case supplies: an object as its subject, and arguments for its input parameters by position or by name.

type AnalysisEvaluation

type AnalysisEvaluation struct {
	// Function is the qualified name of the calc applied.
	Function string

	// Arguments are what the calc was applied to, by parameter position, a named
	// one at its parameter's; null where none was given before a later one.
	Arguments []Value

	// Result is what the calc computed; unset when Error says why it computed nothing.
	Result Value
	Error  error

	// Selected marks the evaluation of the value `selectOne` picked and the case
	// returned. Tied marks one computing what the selected did, passed over for it.
	Selected bool
	Tied     bool
}

AnalysisEvaluation is one application, during a case's run, of a calc held as a function value: a trade study's evaluation of one alternative.

type AnalysisResult

type AnalysisResult struct {
	// Case is the qualified name of the case that ran.
	Case string

	// Subject is the object the case ran on — supplied, bound by the usage or
	// taken from the enclosing case; nil for a case declaring no subject.
	Subject *Instance

	// Inputs are the values the run bound the case's input parameters to, in
	// declaration order, the subject parameter excluded: what the body ran with.
	Inputs []InputBinding

	// Outputs are the case's out and return parameters, in declaration order;
	// a value the body returned into an unnamed result is named "result".
	Outputs []CalcOutputValue

	// Verdicts are the case's objectives, in order, then its assertions.
	Verdicts []AnalysisVerdict

	// Evaluations are the applications of the case's own calcs as function values
	// the run made, in the order first made, once per distinct argument list.
	Evaluations []AnalysisEvaluation
}

AnalysisResult is what one run of an analysis case produced: its output values in declaration order, and the verdict of each objective and assertion.

type AnalysisVerdict

type AnalysisVerdict struct {
	// Kind is "objective" or "assertion".
	Kind string

	// Name names the objective or the asserted constraint usage, or spells an
	// anonymous assertion's condition as written.
	Name string

	// Symbol declares the objective or the named constraint asserted; nil for an
	// anonymous assertion.
	Symbol *symbols.Symbol

	// Status is what the check decided.
	Status VerdictStatus

	// Detail is the violated condition of a failed check, or why an undecided
	// one could not be evaluated; empty for a satisfied one.
	Detail string
}

AnalysisVerdict is what one check of an analysis case decided after its body ran: an objective's required conditions, or an assertion in its body.

type ArgumentError added in v0.11.0

type ArgumentError struct {
	Index int
	Err   error
}

ArgumentError reports the argument of an argument list, by position, whose evaluation failed.

func (*ArgumentError) Error added in v0.11.0

func (e *ArgumentError) Error() string

func (*ArgumentError) Unwrap added in v0.11.0

func (e *ArgumentError) Unwrap() error

Unwrap returns the evaluation error itself.

type Array

type Array struct {
	Dimensions []int64
	Elements   []Value
	// Object is the Collections::Array object the value was read from, which keeps
	// answering the members a specialization adds; 0 for an array made by value.
	Object int64
}

Array is a Collections::Array: its `dimensions` and its `elements` flattened in row-major order. `rank` and `flattenedSize` derive from the dimensions.

func (*Array) Format

func (a *Array) Format(element func(Value) string) string

Format renders `Array(2, 2)[1, 2, 3, 4]` with each element rendered by element; an array of rank 0 is `Array()[7]`.

func (*Array) Rank

func (a *Array) Rank() int

Rank is the number of dimensions.

type Asserted added in v0.11.0

type Asserted struct {
	Kind AssertionKind
	// Symbol is the asserting usage and Scope the scope its conditions resolve in.
	Symbol *symbols.Symbol
	Scope  *symbols.Scope
	// Text is the assertion as written, so an anonymous one can be named.
	Text string
	// contains filtered or unexported fields
}

Asserted is one assertion a type states about every object of it: an asserted or invariant constraint, a requirement it carries, or a satisfy usage.

type AssertionKind

type AssertionKind string

AssertionKind is the kind of assertion an object verdict is about.

const (
	AssertionConstraint   AssertionKind = "constraint"
	AssertionRequirement  AssertionKind = "requirement"
	AssertionSatisfaction AssertionKind = "satisfaction"
)

type BodySteps added in v0.10.0

type BodySteps struct {
	Stmts     []lower.Statement
	Scope     *symbols.Scope
	Node      ast.Node // first statement, for spans
	Order     *lower.StatementOrder
	Footprint lower.Footprint
}

BodySteps is the statements one constraint body performs before its conditions are evaluated, with the body scope for spans and name resolution.

type Bring

type Bring func(id int64) (*Instance, error)

Bring answers, for an object of another context, the object of this one that stands for it; an error when none does.

type Budgets

type Budgets struct {
	MaxSteps       int64
	MaxActionSteps int64
	MaxStateEvents int64
	MaxDoSteps     int64
	MaxElements    int64
	MaxCalcDepth   int64
	MaxSweepRuns   int64
	MaxIntegerBits int64
}

Budgets bounds one run of the runtime, and how many runs one sweep asks for. The bounds count incommensurable things — expression evaluations, action token-flow steps, state machine events, do actions, materialized collection elements, nested calc invocations, swept runs and the bits of one Integer — so raising one says nothing about the others.

func BudgetsFromEnv

func BudgetsFromEnv() (Budgets, error)

BudgetsFromEnv returns the bounds the environment asks for: for each variable the positive integer it holds, or the default when it is unset or empty. Every unusable value is reported, naming its variable and the value, so a typo is reported instead of silently leaving the default in place.

func DefaultBudgets

func DefaultBudgets() Budgets

DefaultBudgets returns the bounds a run uses when the environment names no override.

func (Budgets) Validate

func (b Budgets) Validate() error

Validate reports every bound that is not positive, which would let a run make no progress at all, below its floor, or above its ceiling, which would fail unrecoverably.

type Builtin

type Builtin struct {
	Name   string
	FQN    string
	Params []string
	// Collection is true for the operations over sequences, collections and
	// bodies, which are the ones written in the postfix `x->name()` form.
	Collection bool
	// Package is the library package that declares the function, which a model
	// imports for a call by the unqualified name to be legal: the name resolves
	// as any other does, so `import RealFunctions::*;` is what makes a bare
	// `sqrt(x)` denote RealFunctions::sqrt.
	Package string
}

Builtin is one library function this runtime implements directly, described for a caller that lists them: the unqualified name a call may use, the library declaration that name denotes, and the parameter names of that declaration when the registry knows them.

func Builtins

func Builtins() []Builtin

Builtins returns every library function this build implements that a model calls by name, in name order, each with the package a call by that name needs imported. It is the registry behind the REPL's %builtins listing, so what the REPL advertises is what this build implements. A declaration registered only to report itself as not evaluable is left out, as is one named as an operator, which a model writes as that operator rather than as a call.

type CalcOutputValue

type CalcOutputValue struct {
	Name  string
	Value Value
}

CalcOutputValue is the value one output feature of a calc usage took, in the order the calc declares its outputs.

type Call

type Call struct {
	Operation string
	Declared  *symbols.Symbol
	Args      map[string]Value
}

Call is the payload of an eventCall: the operation invoked, its declaration as a behavior member of the machine's owner (nil when it declares none) and the arguments.

type CheckArgs added in v0.10.0

type CheckArgs struct {
	Positional []Value
	Named      map[string]Value
}

CheckArgs are the values a check of a constraint or requirement supplies for its `in` parameters: by position in declaration order, the subject never among them, or by name. The zero value supplies nothing.

type CheckBudget

type CheckBudget struct {
	Depth  int
	States int
}

CheckBudget bounds a check: the moves one schedule may make and the distinct states the search may visit; 0 leaves either unbounded.

type CheckFinal

type CheckFinal struct {
	Outcome string
	Values  map[string]string
	Witness Witness
	// contains filtered or unexported fields
}

CheckFinal is one distinct outcome of the complete schedules and a schedule reaching it; Values spells every feature divergence is reported over, the performing object's as `this.<name>`, and Outcome spells the action's outputs with the object's values after them.

type CheckOptions

type CheckOptions struct {
	// Diverge names the features whose divergence is reported: the action's own
	// bare, a performed node's as `node.pin`, the performing object's as `this.<name>`;
	// none names the action's own features and the object's attributes. A name
	// no feature answers to fails the check (ErrUnknownCheckFeature).
	Diverge []string
	// Reduce explores one representative of each class of equivalent schedules;
	// off, every schedule. It is off only to test that the reduction loses nothing.
	// A check with properties searches unreduced: what a property reads is not
	// in the footprints the reduction is sound for.
	Reduce bool
}

CheckOptions selects what a check reports and how it searches.

type CheckProperty

type CheckProperty struct {
	Name  string
	Holds func(*Context, *Invocation) (bool, error)
}

CheckProperty is a property evaluated at every stable state of a check: a requirement or constraint, false at a state being a violation. Holds is asked in the check's context of the invocation the check runs, and again of a replay of the witness that claims it false or failing to evaluate.

type CheckReport

type CheckReport struct {
	Verdict CheckVerdict
	// States counts the distinct states visited; Moves the moves made; MaxDepth
	// the longest schedule searched.
	States   int
	Moves    int
	MaxDepth int
	// BoundsHit names the search and statement-order bounds it ran into, and the
	// executor's budgets by name (ExecutorBounds); none when exhaustive.
	BoundsHit []string
	// Limits are the executor's budgets the search ran under.
	Limits Budgets
	// Horizon is the instant the search stopped the clock at: no schedule was
	// followed past it, and a state there is final.
	Horizon    Horizon
	Violations []Violation
	Divergent  []Divergence
	// Finals are the distinct outcomes of the complete schedules, in canonical order.
	Finals []CheckFinal
	// Unenumerated are the constructs whose unordered alternatives the searched
	// runs took in one order without a choice point, so a clean report observed
	// rather than bounded the result.
	Unenumerated []CoverageGap
	// Scope is the distinct reasons the finals were observed short of quiescence.
	Scope []ObservationReason
	// MassBounded reports the violations' masses are lower bounds: they are when a
	// bound kept schedules out, moves left an interleaving out, a state was reached
	// again, or the reduction left a move unexplored at a state.
	MassBounded bool
}

CheckReport is what a check of the schedules of an action found.

func Check

func Check(stop context.Context, fresh func() (*Context, error), start Starter, budget CheckBudget, opts CheckOptions, props []CheckProperty) (*CheckReport, error)

Check searches the schedules of the invocation start begins in the context fresh makes. Every violation and every final value carries the witness a replay of the same starter follows (Replay). It stops with a CheckStopped when stop ends first; it fails when the run refused a move it selected. The start draws choice points itself (region entry order), so it is begun once per way of resolving them and the search runs from every state a start reaches.

func (*CheckReport) Status

func (r *CheckReport) Status() string

Status renders how the check ended for a report.

type CheckResult

type CheckResult struct {
	Holds       bool
	Subject     *Instance
	SubjectRoot *Instance
	SubjectPath []string

	// Vacuous says why a holding requirement check judged no condition: it
	// states no required constraint. Empty for a verdict about conditions.
	Vacuous string
}

CheckResult is the outcome of one check: whether it holds, the object its conditions were evaluated against — nil when they were evaluated against the declaration because no object carries the checked element — and, for a nested subject, the object the search started from plus the features walked from it, one name a segment — ending in the declaration the object materializes, as an ambiguity names it — which are how a caller names an object holding no name of its own.

type CheckStopped

type CheckStopped struct {
	States   int
	Moves    int
	MaxDepth int
	Cause    error
}

CheckStopped is a check the caller stopped before it ended, with what it had searched so far; it unwraps to the caller's reason.

func (*CheckStopped) Error

func (e *CheckStopped) Error() string

func (*CheckStopped) Unwrap

func (e *CheckStopped) Unwrap() error

type CheckVerdict

type CheckVerdict int

CheckVerdict is how a check ended.

const (
	// CheckExhaustive found no violation and every schedule, up to equivalence, was searched.
	CheckExhaustive CheckVerdict = iota
	// CheckWithinBounds found no violation among the schedules the bounds let it search.
	CheckWithinBounds
	// CheckViolation found a violation.
	CheckViolation
	// CheckDivergent found no violation and a feature whose final value the schedule decides.
	CheckDivergent
)

func (CheckVerdict) String

func (v CheckVerdict) String() string

type ChoiceKind

type ChoiceKind int

ChoiceKind names what an executor chose among at a choice point.

const (
	// ChoiceTokenOrder: several tokens were steppable in one step, and the step
	// advanced them in an order the library does not fix.
	ChoiceTokenOrder ChoiceKind = iota
	// ChoiceDecisionBranch: several guards of one decision node held.
	ChoiceDecisionBranch

	// ChoiceTransition: several transitions out of one state were enabled for
	// one event.
	ChoiceTransition
	// ChoiceRegionOrder: one event enabled transitions in several regions, which
	// fired in an order the library does not fix.
	ChoiceRegionOrder
	// ChoiceDueOrder: several executors had work due at one instant of the
	// shared clock, and one of them ran first.
	ChoiceDueOrder
)

func (ChoiceKind) String

func (k ChoiceKind) String() string

String is the kind as a trace or diagnostic names it.

type ChoiceParseError

type ChoiceParseError struct {
	// Line is the 1-based line of the witness, 0 for a line parsed on its own.
	Line   int
	Text   string
	Reason string
}

ChoiceParseError reports a line of a witness that spells no choice, with why.

func (*ChoiceParseError) Error

func (e *ChoiceParseError) Error() string

func (*ChoiceParseError) Is

func (e *ChoiceParseError) Is(target error) bool

Is makes every ChoiceParseError match errInvalidChoice.

type ChoicePoint

type ChoicePoint struct {
	Kind ChoiceKind
	// Step is the action step the choice was made in, 0 for a state machine.
	Step int
	// Where names the decision node, the state and event, or the instant of a
	// due order; empty for a token order.
	Where string
	// Alternatives are canonical: tokens by ID, branches and transitions by
	// declaration position, writes by writing token, reacting states by name in
	// declaration order, executors due at one instant in the order they were
	// created, tied events in arrival order. Taken indexes the one taken.
	Alternatives []string
	Taken        int
	// Weights are the probabilities the model states for the alternatives of a
	// weighted decision, one per alternative; nil for a choice the model does not weight.
	Weights []float64
	// Drew is the unit draw that selected Taken among the Weights, when Drawn.
	Drew  float64
	Drawn bool
	// File and Span locate the declaration the choice was made at; File is ""
	// when the runtime could not name one.
	File string
	Span source.Span
	// Independent reports that the alternatives commute by their lowered
	// footprints: whichever is taken, the run's values are the same, so the
	// choice leaves no value order-dependent.
	Independent bool
	// Touches are the features the conflicting alternatives write, sorted; the
	// run's value of each is order-dependent on this choice.
	Touches []string
	// contains filtered or unexported fields
}

ChoicePoint is one point where an executor had several enabled alternatives the Kernel Semantic Library leaves unordered and took one by its own scheduling rule.

func (ChoicePoint) Choice

func (c ChoicePoint) Choice() ChoiceTaken

Choice is the choice point as a witness lists it: what ChoiceTaken.String spells and ParseChoice reads back.

func (ChoicePoint) Describe

func (c ChoicePoint) Describe() string

Describe renders the choice for a diagnostic: the alternatives in canonical order and which one the executor took; a weighted decision's alternatives carry their weights and how the branch was selected.

func (ChoicePoint) Diagnostic

func (c ChoicePoint) Diagnostic() diag.Diagnostic

Diagnostic is the choice as a finding about the run: informational, since a model is not wrong for admitting several orders and the run took one of them.

func (ChoicePoint) Location

func (c ChoicePoint) Location() (string, source.Span)

Location is where the choice was made.

func (ChoicePoint) Standing added in v0.11.0

func (c ChoicePoint) Standing() string

Standing is what the choice leaves open: `independent` when its alternatives commute by their footprints, else `order-dependent`, naming the features the conflicting alternatives wrote.

func (ChoicePoint) String

func (c ChoicePoint) String() string

String is the trace line the choice is recorded as.

type ChoiceTaken

type ChoiceTaken struct {
	Kind ChoiceKind
	// Step is the action step the choice was made in, 0 for a state machine.
	Step int
	// Where names the decision node or the state and event; empty for a token order.
	Where string
	// Alternatives is how many the point had; Taken indexes the one taken.
	Alternatives int
	Taken        int
	// Among names the alternatives as a trace does; Took is the one taken: the
	// token tried next, a branch or a transition by declared position and target,
	// or the state whose transition fired first.
	Among []string
	Took  string
	// Weights are the probabilities the model states for the alternatives, one
	// per alternative, for a weighted decision; nil for a choice it does not weight.
	Weights []float64
	// Drew is the unit draw that selected Taken among the Weights, when Drawn.
	Drew  float64
	Drawn bool
}

ChoiceTaken is one choice point of a run and the alternative it took, as the witness of an outcome lists them.

func ParseChoice

func ParseChoice(text string) (ChoiceTaken, error)

ParseChoice reads one choice as ChoiceTaken.String spells it: `step N: T first of A, B`, `step N: decision D -> B`, `S -> T`, `W: X first of A, B` (a region order, a due order at `t=…`, or a dispatch order among `events at t=…`), `step N: statements in …: X first of A, B`.

func ParseChoices

func ParseChoices(text string) ([]ChoiceTaken, error)

ParseChoices reads the choices of a witness header naming no object and spelling no input: as ChoiceTaken.String spells them, one per line or joined by `; `, ending at the first blank line after it; what follows is ignored.

func (ChoiceTaken) String

func (c ChoiceTaken) String() string

String renders the choice for a table or a failure message, as ParseChoice reads it back: a name the line's own punctuation occurs in is quoted, and a weighted branch carries the alternatives with their weights and the draw.

type Clock

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

Clock is the simulation time every executor of one context shares: the current instant in seconds and the executors whose waits it reads in due order.

func (*Clock) NextDue

func (c *Clock) NextDue() (float64, bool)

NextDue returns the earliest instant a wait comes due at past the current one, false when nothing waits on the clock.

func (*Clock) Now

func (c *Clock) Now() float64

Now returns the current simulation instant, in seconds.

func (*Clock) Waits

func (c *Clock) Waits() []ClockWait

Waits lists everything waiting on the clock for an instant it has not reached, by due instant and, at one instant, by the executors' creation order.

type ClockWait

type ClockWait struct {
	// Due is the instant the wait comes due at, in seconds.
	Due float64
	// contains filtered or unexported fields
}

ClockWait describes one wait on the clock for a view of the run.

func (ClockWait) Holder

func (w ClockWait) Holder() string

Holder names the executor waiting.

func (ClockWait) What

func (w ClockWait) What() string

What describes the wait itself.

type Condition

type Condition struct {
	// Expr is the condition's expression, nil for a group.
	Expr ast.Node

	// Scope is where Expr's names resolve, or the type a Conflict is found on;
	// nil for a group.
	Scope *symbols.Scope

	// Group is the conditions a body states, all of which must hold; nil for a
	// condition stating an expression.
	Group []Condition

	// Steps are the statements the body performs before its Group's conditions
	// are evaluated, as one Boolean function performance; nil for a condition
	// or a group stating none.
	Steps *BodySteps

	// Conflict is a second result expression, stated or inherited (KerML
	// 8.3.4.8); no verdict is reached. Nil otherwise.
	Conflict *semantics.ResultExpressionConflict

	// Negated is the negation the declaration wrote, applied to Expr or to the
	// whole conjunction Group stands for.
	Negated bool

	// Required distinguishes a required condition from an assumption, which is
	// trusted rather than required to hold.
	Required bool

	// Constraints are the named constraint usages stating the condition through
	// their types, outermost first: each one's parameter values mask the
	// enclosing ones', which mask the checked element's. empty reads the latter alone.
	Constraints []*symbols.Symbol

	// Circular is the requirement a `require r` names while r's own conditions
	// are being collected: a reference back into the check, stating nothing evaluable.
	Circular *symbols.Symbol
}

Condition is one boolean check a constraint or requirement states, with the scope its expression resolves names in. A condition states either an expression or a group, which holds when all of its conditions hold.

func (Condition) Label

func (c Condition) Label() string

Label renders the condition as written, negation and grouping included.

func (Condition) Owner

func (c Condition) Owner() *symbols.Symbol

Owner is the nearest named element declaring the condition (the supertype an inherited one came from), or nil; a body-local or anonymous scope is skipped.

type ConnectorEnd

type ConnectorEnd struct {
	Name string
	// Feature is the end's own declaration, when the model registers one: through
	// it the end's value is a value of every feature the end subsets.
	Feature *symbols.Symbol
	Value   Value
}

ConnectorEnd is one end of a materialized connector: the name of the end feature it occupies, empty for an end the model leaves unnamed, and the value the end attaches to. The value is the connected feature itself — an object held at an end is the very object the connected feature holds, not a copy of it (KerML 1.0 §7.4.6) — so writing through one is read through the other.

type Context

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

Context is the run-derived state of one execution over a Model: the objects it created, their values and lifetimes, the messages in flight, the clock, the executors' progress. A snapshot captures it; the Model it runs over is shared with every other run of the same model and is not part of it.

func NewContext

func NewContext(model *Model, maxSteps int64) *Context

NewContext creates a run's context over the model-derived part model. maxSteps sets the runaway guard (step counter limit); the executor bounds take their defaults, which SetBudgets replaces. It panics if maxSteps <= 0: the limit is a programmer-supplied invariant, not user input, so callers must pass a positive value.

func (*Context) ActionInputs added in v0.9.2

func (ctx *Context) ActionInputs(scope *symbols.Scope, sym *symbols.Symbol, positional []Value, named []NamedInput) (map[string]Value, error)

ActionInputs is the inputs an invocation of sym binds, as bindArgumentList binds them: the positional arguments to the first `in` parameters in declaration order, then the named ones in their order — each written name resolved through BoundParameter as an invocation's is. More positional arguments than parameters is errActionArity, a name no `in` parameter carries is errUnknownParameter, and one already bound is errDuplicateArgument.

func (*Context) ActionOutcome

func (ctx *Context) ActionOutcome(outputs map[string]Value) Outcome

ActionOutcome is the outcome of an action run: the values its features hold.

func (*Context) ActionOutcomePerformedBy

func (ctx *Context) ActionOutcomePerformedBy(action *symbols.Symbol, self *Instance, inputs map[string]Value) (Outcome, error)

ActionOutcomePerformedBy runs an action as ExecuteActionPerformedBy does and reports the outcome an exploration compares: its features and, under `this.`, the performer's attributes.

func (*Context) Adopt

func (ctx *Context) Adopt(prev *Context, shapes *Shapes, obj *Instance) ([]string, error)

Adopt takes obj — and every object it holds — over from prev into this context, keeping the identity and the values they carry across a re-analysis of the document they were materialized from. Each object is rebound to the declaration of the same qualified name here, which must resolve to the shape recorded in shapes; anything else is refused with the context left untouched. The objects are moved rather than copied, so prev holds them too afterwards and this context takes over its identity sequence; nothing new should be materialized through prev, which registers it there alone.

A behavior a carried object ran belongs to the analysis it started in, so it is started again here from its initial state rather than continued. The behaviors restarted are returned, so the carry-over reports what it cost.

func (*Context) AdoptIdentities

func (ctx *Context) AdoptIdentities(prev *Context)

AdoptIdentities takes over the identity sequence of a context this one replaces, without carrying any object over: objects a run started before still materializes through it, so neither context may hand out the other's.

func (*Context) Advance

func (ctx *Context) Advance(duration float64) (AdvanceReport, error)

Advance moves the clock by duration seconds, running everything due on the way instant by instant; a wait due later stays queued and nothing waiting is no error. The duration and the instant it leads to must be finite.

func (*Context) AdvanceUntil

func (ctx *Context) AdvanceUntil(duration float64, halted func() bool) (AdvanceReport, error)

AdvanceUntil is Advance stopping early, the clock held at the instant whose due work made halted true — a debugger's breakpoint — before moving on.

func (*Context) AnalysisOutcome

func (ctx *Context) AnalysisOutcome(r AnalysisResult) Outcome

AnalysisOutcome is the outcome of a case's run: its outputs, and each verdict as a value named by the objective or assertion it decided.

func (*Context) AssertionsOf added in v0.11.0

func (ctx *Context) AssertionsOf(typ *symbols.Symbol, scope *symbols.Scope) []Asserted

AssertionsOf lists the assertions typ states about its objects, inherited ones first, a named one a closer member shadows or redefines left out: the same collection validating an object of typ checks. scope stands in for typ's own.

func (*Context) BehaviorNamed

func (ctx *Context) BehaviorNamed(inst *Instance, name string) (*ObjectBehavior, bool)

BehaviorNamed returns the behavior the object runs under the given name or under another name of the same feature: a redefinition renames the behavior it redefines (KerML 1.0 §7.3.4.5), so both names denote one execution. The renaming may come from any type of the object, a classifier included.

func (*Context) Budgets

func (ctx *Context) Budgets() Budgets

Budgets returns the bounds this context runs under.

func (*Context) CalcCompile

func (ctx *Context) CalcCompile() bool

CalcCompile reports whether this context runs eligible calc bodies compiled.

func (*Context) CalcUsageOutputs

func (ctx *Context) CalcUsageOutputs(sym *symbols.Symbol, scope *symbols.Scope, self *Instance) ([]CalcOutputValue, error)

CalcUsageOutputs evaluates a calc usage and returns the value of every output feature it declares, in declaration order, from one run of its body.

func (*Context) Carry

func (ctx *Context) Carry(v Value, bring Bring) (Value, error)

Carry is v as a value of ctx: a number, string, quantity or the like as it is; every object it names is the one bring answers for it; a function is read again here, bound to what bring answers for its self. A deferred expression closed over its environment, or a function over a behavior body, cannot be carried.

func (*Context) CaseConditionsOf

func (ctx *Context) CaseConditionsOf(sym *symbols.Symbol, scope *symbols.Scope) []Condition

CaseConditionsOf returns the conditions a case states as what it holds true of its parameters: the conditions its own members state, and the ones stated by the constraints it requires, assumes or asserts in its body. A constraint declared without one of those keywords states nothing the case checks, so it is left out.

func (*Context) Changed

func (ctx *Context) Changed(shapes *Shapes) (string, bool)

Changed returns the declaration this context no longer resolves the way shapes recorded it, so a caller can name what invalidated the state it took those shapes for. They were recorded outwards, so reading them back names the one that changed rather than one that only holds it.

func (*Context) CheckConstraintOn

func (ctx *Context) CheckConstraintOn(sym *symbols.Symbol, scope *symbols.Scope, self *Instance) (CheckResult, error)

CheckConstraintOn evaluates a constraint as EvaluateConstraintOn does and also reports the object it turned out to be about, which a caller labelling the verdict needs: it is not always the instance supplied.

func (*Context) CheckConstraintWith added in v0.10.0

func (ctx *Context) CheckConstraintWith(sym *symbols.Symbol, scope *symbols.Scope, self *Instance, args CheckArgs) (CheckResult, error)

CheckConstraintWith is CheckConstraintOn with arguments bound to the constraint's `in` parameters for this check, as a calc's are for an invocation.

func (*Context) CheckPerformedInputs added in v0.11.0

func (ctx *Context) CheckPerformedInputs(action *symbols.Symbol, behavior *ObjectBehavior, inputs map[string]Value) error

CheckPerformedInputs is refusePerformedInputs for a caller attaching to the performance itself: inputs equal to the bindings the performance stored, or its declaration states while it is held, pass; any other is refused.

func (*Context) CheckRequirementOn

func (ctx *Context) CheckRequirementOn(sym *symbols.Symbol, scope *symbols.Scope, self *Instance) (CheckResult, error)

CheckRequirementOn evaluates a requirement as EvaluateRequirementOn does and also reports the object it turned out to be about.

func (*Context) CheckRequirementWith added in v0.10.0

func (ctx *Context) CheckRequirementWith(sym *symbols.Symbol, scope *symbols.Scope, self *Instance, args CheckArgs) (CheckResult, error)

CheckRequirementWith is CheckRequirementOn with arguments bound to the requirement's `in` parameters for this check, as a calc's are for an invocation.

func (*Context) CheckSatisfactionOn

func (ctx *Context) CheckSatisfactionOn(a *SatisfyAssertion, subject *Instance) (CheckResult, error)

CheckSatisfactionOn evaluates a satisfaction assertion as evaluateSatisfactionOn does and also reports the object it turned out to be about.

func (*Context) Choices

func (ctx *Context) Choices() []ChoicePoint

Choices returns the choice points made since the latest run began, in order.

func (*Context) ClassifyValue added in v0.11.0

func (ctx *Context) ClassifyValue(scope *symbols.Scope, value Value, target *symbols.Symbol) (semantics.TypeClassification, error)

ClassifyValue reports whether the value, read in scope, is of the target type by any of the types it carries.

func (*Context) ClearModelSeed

func (ctx *Context) ClearModelSeed()

ClearModelSeed leaves modeled draws to the scheduling policy's seed, if any.

func (*Context) Clock

func (ctx *Context) Clock() *Clock

Clock returns the simulation clock every executor of this context shares.

func (*Context) ClockMagnitude

func (ctx *Context) ClockMagnitude(val Value, what string) (float64, error)

ClockMagnitude reads a value as a number of clock units: a bare number is one already, a quantity is converted from its unit; what names it in errors.

func (*Context) ClockStep

func (ctx *Context) ClockStep() float64

ClockStep is the step the clock's waits come due on, 0 for a continuous clock.

func (*Context) ClockValue

func (ctx *Context) ClockValue() Value

ClockValue is the clock's instant now as a value: a duration in seconds, or a bare number where no library reduces the second.

func (*Context) CompositeTypeOf

func (ctx *Context) CompositeTypeOf(feat *EffectiveFeature) *symbols.Symbol

CompositeTypeOf returns what a feature is materialized from, or nil for one that holds a value rather than an object — a default that binds takes precedence over instantiation, as in GetFeatureValue above. A usage with features of its own is instantiated as itself, so its body governs and an untyped nested part materializes at all. Answering costs no allocation, so a caller walking an object graph can decide whether to descend before descending.

func (*Context) ConditionCarrier added in v0.9.2

func (ctx *Context) ConditionCarrier(kind, element string, sym *symbols.Symbol, self *Instance) (*Instance, error)

ConditionCarrier is the object a check of sym is about, resolved as evaluation resolves it — self when it carries the element, else the single object of this runtime that does — with the same error, ambiguity included, an evaluation reports.

func (*Context) ConditionsOf

func (ctx *Context) ConditionsOf(sym *symbols.Symbol, scope *symbols.Scope) []Condition

ConditionsOf returns the conditions sym states, its inherited ones first: the same collection, in the same order, that evaluating sym checks. scope stands in for sym's own scope when sym declares none.

func (*Context) CreateActionExecutor

func (ctx *Context) CreateActionExecutor(action *symbols.Symbol) (*ActionExecutor, error)

CreateActionExecutor creates an action executor without starting execution. For REPL debugging - allows step-by-step execution control.

func (*Context) CreateActionExecutorFor

func (ctx *Context) CreateActionExecutorFor(action *symbols.Symbol, self *Instance) (*ActionExecutor, error)

CreateActionExecutorFor creates an action executor for an action performed by self, without starting execution. An action a ToolExecution annotates has no flow to step: its tool is invoked once and the executor returned completed with its outputs.

func (*Context) CreateActionExecutorWithInputs

func (ctx *Context) CreateActionExecutorWithInputs(action *symbols.Symbol, self *Instance, inputs map[string]Value) (*ActionExecutor, error)

CreateActionExecutorWithInputs creates an action executor for an action performed by self with its inputs bound ahead of its defaults, without starting execution.

func (*Context) CreateStateExecutor

func (ctx *Context) CreateStateExecutor(stateMachine *symbols.Symbol) (*StateExecutor, error)

CreateStateExecutor creates a state executor without starting execution. For REPL debugging - allows step-by-step execution control.

func (*Context) CreateStateExecutorFor

func (ctx *Context) CreateStateExecutorFor(stateMachine *symbols.Symbol, self *Instance) (*StateExecutor, error)

CreateStateExecutorFor creates a state executor for a machine performed by self, without starting execution.

func (*Context) Destroyed

func (ctx *Context) Destroyed(inst *Instance) (at int64, ok bool)

Destroyed reports the activation at which inst was destroyed, and whether it was; an object the context holds without a lifetime or one merely ended is not.

func (*Context) DrawPolicy

func (ctx *Context) DrawPolicy() DrawPolicy

DrawPolicy is the policy the runs started from now on resolve their random draws under.

func (*Context) DrawsTaken

func (ctx *Context) DrawsTaken() []DrawTaken

DrawsTaken returns the random draws every run of the context made, in order, as a witness lists them: what a `replay` policy over them hands the same calls.

func (*Context) ElementAt added in v0.10.0

func (ctx *Context) ElementAt(val Value, index int) (Value, error)

ElementAt is the value at the 0-based index of a collection, a required member's object made once it is reached; any other value is its only element.

func (*Context) EnumerationLiteralValue

func (ctx *Context) EnumerationLiteralValue(sym *symbols.Symbol) (Value, bool, error)

EnumerationLiteralValue is the value sym has when it is an enumeration literal, reported as such so a caller holding only a symbol — an `%eval` of a literal — answers with the value rather than "no value".

func (*Context) Eval

func (ctx *Context) Eval(node ast.Node) (Value, error)

Eval is the top-level entry point for evaluating an expression in an empty environment. Resolves names from the root scope.

func (*Context) EvalArguments added in v0.11.0

func (ctx *Context) EvalArguments(scope *symbols.Scope, args []ast.Node) ([]Value, error)

EvalArguments evaluates an invocation's whole argument list in one run, so a seeded draw continues the one before it; the i-th value is the i-th argument's, or an ArgumentError.

func (*Context) EvalDeclaredValue

func (ctx *Context) EvalDeclaredValue(sym *symbols.Symbol) (Value, error)

EvalDeclaredValue evaluates the value a usage declaration binds, as a read of the declaration does: in its own scope, and answering to its declared type. A usage binding none but shaped as an Array by its own features is that Array.

func (*Context) EvalWithScope

func (ctx *Context) EvalWithScope(node ast.Node, scope *symbols.Scope) (Value, error)

EvalWithScope evaluates an expression with a given scope context for name resolution.

func (*Context) EvalWithScopeOn

func (ctx *Context) EvalWithScopeOn(node ast.Node, scope *symbols.Scope, self *Instance) (Value, error)

EvalWithScopeOn evaluates an expression against a concrete instance, so a feature it names reads that object's feature value. It brackets one run, as EvalWithScope does, which is what bounds the evaluation by the step budget.

func (*Context) EvaluateConstraint

func (ctx *Context) EvaluateConstraint(sym *symbols.Symbol, scope *symbols.Scope) (bool, error)

EvaluateConstraint evaluates a constraint definition/usage naming no object: against the single object of this runtime carrying it, the declared defaults when there is none, ErrAmbiguousSubject when there are several. Checked against the defaults, `this` denotes an exemplar of the type made for the check and abandoned with it (exemplar.go). Returns (satisfied, error). If IsAssert=true, violation is an error. If IsAssert=false (assume), always returns (true, nil) but logs assumptions.

func (*Context) EvaluateConstraintOn

func (ctx *Context) EvaluateConstraintOn(sym *symbols.Symbol, scope *symbols.Scope, self *Instance) (bool, error)

EvaluateConstraintOn evaluates a constraint against a concrete instance: a feature the constraint names resolves to that instance's feature value, so the same constraint can pass for one instance and fail for another. An instance that does not carry the constraint itself is searched for the nested object that does; a nil instance leaves the subject to EvaluateConstraint's rule.

func (*Context) EvaluateRequirement

func (ctx *Context) EvaluateRequirement(sym *symbols.Symbol, scope *symbols.Scope) (bool, error)

EvaluateRequirement evaluates a requirement definition/usage naming no object, choosing its subject as EvaluateConstraint does. Returns (satisfied, error). Validates subject/actor types and evaluates assume/require expressions. Assume members always pass (trusted), require members must evaluate to true.

func (*Context) EvaluateRequirementOn

func (ctx *Context) EvaluateRequirementOn(sym *symbols.Symbol, scope *symbols.Scope, self *Instance) (bool, error)

EvaluateRequirementOn evaluates a requirement against a concrete instance, binding the features it names to that instance's feature values. The subject is chosen as EvaluateConstraintOn chooses it, and the subject/actor bindings are evaluated against that same object.

func (*Context) EvaluateSatisfaction

func (ctx *Context) EvaluateSatisfaction(a *SatisfyAssertion) (bool, error)

EvaluateSatisfaction evaluates a satisfaction assertion against a fresh instance of its subject, so that the values the subject declares supply the requirement's own.

func (*Context) ExecuteAction

func (ctx *Context) ExecuteAction(action *symbols.Symbol) (map[string]Value, error)

ExecuteAction executes an action definition/usage to completion. Returns the values the action's features hold when it completed.

func (*Context) ExecuteActionPerformedBy

func (ctx *Context) ExecuteActionPerformedBy(action *symbols.Symbol, self *Instance, inputs map[string]Value) (map[string]Value, error)

ExecuteActionPerformedBy executes an action performed by self, whose connections route what the action sends and whose variant selections decide which of them are realized. A nil self performs the action outside any object.

func (*Context) ExecuteActionReportingPerformer added in v0.9.2

func (ctx *Context) ExecuteActionReportingPerformer(action *symbols.Symbol, self *Instance, inputs map[string]Value) (outputs, performer map[string]Value, err error)

ExecuteActionReportingPerformer runs an action as ExecuteActionPerformedBy does and also reports its performer's attributes, keyed as ActionOutcomePerformedBy keys them.

func (*Context) ExecuteActionWithInputs

func (ctx *Context) ExecuteActionWithInputs(action *symbols.Symbol, inputs map[string]Value) (map[string]Value, error)

ExecuteActionWithInputs executes an action, seeding its feature space with the provided input parameter bindings (keyed by parameter name). Inputs override action attribute defaults of the same name. Returns the final feature values.

func (*Context) ExecuteOccurrence added in v0.11.0

func (ctx *Context) ExecuteOccurrence(sym *symbols.Symbol) (*OccurrenceRun, error)

ExecuteOccurrence performs an occurrence definition or usage as the interaction its body states (SysML v2.1 §7.16.1: a message "may be realized … using transfers from send actions to accept actions"): the occurrence is materialized, and its nodes are visited in the order the events admit. At an event the messages reaching it are taken off the bus by the lifeline object holding it, the actions the event performs are performed once on that object, the constraints it asserts are checked there, and the messages leaving it are posted, typed by their payloads, to the objects holding their target events; at an occurrence usage of a nested interaction, that interaction is performed on the object the usage holds. The trace records each transfer as a send and an accept.

func (*Context) ExecuteState

func (ctx *Context) ExecuteState(stateMachine *symbols.Symbol) (map[string]Value, error)

ExecuteState executes a state machine, processing events until completion or suspension. Returns final state data from the state machine's execution. Execution stops when: - A final state is reached (StateCompleted) - Event queue is empty (StateSuspended) - Max event processing steps exceeded (error)

func (*Context) ExecuteStatePerformedBy

func (ctx *Context) ExecuteStatePerformedBy(stateMachine *symbols.Symbol, self *Instance, events []string) (map[string]Value, []string, error)

ExecuteStatePerformedBy executes a state machine performed by self, whose connections route what the machine sends and whose variant selections decide which of them are realized. A nil self performs it outside any object.

func (*Context) ExecuteStateWithEvents

func (ctx *Context) ExecuteStateWithEvents(stateMachine *symbols.Symbol, events []string) (map[string]Value, []string, error)

ExecuteStateWithEvents executes a state machine, first injecting the provided signal events (by signal-type name) into the event queue, then processing all events until completion or suspension. Returns the final state data and the ordered list of visited state names.

func (*Context) ExhibitsState

func (ctx *Context) ExhibitsState(member, sym *symbols.Symbol) bool

ExhibitsState reports whether member is an exhibit declaration whose objects run sym's machine: member itself, anything its bindings reach, or a type they conform to. Declarations are compared.

func (*Context) FeaturesOf

func (ctx *Context) FeaturesOf(typeSym *symbols.Symbol) []EffectiveFeature

FeaturesOf returns the ordered, deduplicated effective-feature list for the given type symbol. Result: own + inherited − redefined/masked, memoized per symbol.

func (*Context) FeaturesOfObject

func (ctx *Context) FeaturesOfObject(inst *Instance) []ObjectFeature

FeaturesOfObject returns the features of an object under every type of it: the declared type's, then those each classifier adds, in declaration order, each name once.

func (*Context) FunctionValue

func (ctx *Context) FunctionValue(sym *symbols.Symbol) (Value, bool, error)

FunctionValue is the function a read of the declaration sym denotes — a calc definition, or a calc usage with an input no read could supply — closed over its own scope and no object; false when sym is no calc read as one.

func (*Context) HeldElements added in v0.10.0

func (ctx *Context) HeldElements(val Value) ([]Value, error)

HeldElements is what a collection value holds, in order — a lazily held member named by the identity reserved for it, whose object Instance makes — or the value itself when it is no collection. One holding more than the element budget is ErrElementLimitExceeded.

func (*Context) HeldFeatures added in v0.11.0

func (ctx *Context) HeldFeatures(typ *symbols.Symbol) []HeldFeature

HeldFeatures lists the object-holding features of typ the model declares, library-declared ones left out, each with the elements whose assertions an object it holds carries besides the feature's own: what validating an object of typ checks object by object (ValidateObject).

func (*Context) HeldObjects

func (ctx *Context) HeldObjects(inst *Instance) ([]heldObjectEntry, error)

HeldObjects returns the objects inst's object-valued features hold — occurrence usages and structured attributes alike — in feature order then collection order, materializing lazy ones as reading them does. An object reached through several features is listed once, under a scalar feature when it has one. A feature that cannot be read is a HeldObjectsError.

func (*Context) HoldsNoValue

func (ctx *Context) HoldsNoValue(val Value) bool

HoldsNoValue reports whether a value is an object materialized for a valueless feature of a value type. Such an object has no feature that could hold a value and is no value itself (KerML: a DataType classifies values), so it reads as unset rather than as an object.

func (*Context) HoldsObject

func (ctx *Context) HoldsObject(val Value) bool

HoldsObject reports whether the value is, or carries, an object of this context: one a reader can inspect, so the value is only meaningful in the context it came from.

func (*Context) Image

func (ctx *Context) Image(objects ...*Instance) (*HeldImage, error)

Image takes the objects and everything they hold, own or name by value. It refuses, in a HeldImageError, a destroyed root (errOccurrenceDestroyed), ErrSnapshotMidRun, ErrSnapshotPausedBody, notPortableError and errImageBound.

func (*Context) ImpliedCollection added in v0.9.2

func (ctx *Context) ImpliedCollection(inst *Instance, name string) bool

ImpliedCollection reports whether the feature of inst named name is reached only through subsetting implied by nesting: enumeration surfaces skip it, an object it holds being listed under the declared feature that holds it.

func (*Context) ImpliedCollectionOfType added in v0.9.2

func (ctx *Context) ImpliedCollectionOfType(typ *symbols.Symbol, name string) bool

ImpliedCollectionOfType is ImpliedCollection for a type alone, over the features its instances would hold.

func (*Context) Instance

func (ctx *Context) Instance(id int64) (*Instance, bool)

Instance retrieves an instance by ID, so a caller holding a ValInstance can reach the object it names.

func (*Context) InstanceCount

func (ctx *Context) InstanceCount() int

InstanceCount is how many objects this context holds, nested ones counted.

func (*Context) InstanceIDs

func (ctx *Context) InstanceIDs() []int64

InstanceIDs lists the identities of every object this context holds, in ascending order, so a caller can say which ids an unknown one is not among.

func (*Context) InstantValue

func (ctx *Context) InstantValue(t float64) Value

InstantValue is instant t as the runtime reports the clock: a quantity in seconds when the library defines them, otherwise a bare real.

func (*Context) Instantiate

func (ctx *Context) Instantiate(sym *symbols.Symbol) (*Instance, error)

Instantiate materializes an instance of the given usage/definition symbol. Allocates ID, creates feature values per FeaturesOf(sym), evaluates default values, leaves composite features lazy, then starts the behaviors the type exhibits or performs and runs them to quiescence. Returns the instance or an error.

Each call materializes a distinct object with an identity and behaviors of its own. The object becomes what the usage denotes from then on, so an expression naming the usage or a feature path under it reads this object as it was run.

func (*Context) InstantiateRead

func (ctx *Context) InstantiateRead(sym *symbols.Symbol, read func(*Instance) error) (*Instance, error)

InstantiateRead is Instantiate with read run over the new object before it is returned, as one creation: a read that fails abandons the object with all it materialized, so a context under a bound is left as it was.

func (*Context) InvokeCalc

func (ctx *Context) InvokeCalc(sym *symbols.Symbol, args []Value, scope *symbols.Scope) (Value, error)

InvokeCalc invokes a calculation with the given positional arguments and returns its result. Arguments bind to the calc's input parameters in declaration order; a parameter with no argument falls back to its declared default. The body is evaluated in the calc's own scope, so scope is used only as a fallback for a symbol that owns no scope. A library function's `expr` parameter takes a body or expression value, applied only when selected, or the operand's value itself.

func (*Context) InvokeCalcWith

func (ctx *Context) InvokeCalcWith(sym *symbols.Symbol, positional []Value, named map[string]Value, scope *symbols.Scope) (Value, error)

InvokeCalcWith invokes a calculation with positional arguments and arguments bound by parameter name together, which is what an argument list plus a swept parameter binds. Arguments bind exactly as InvokeCalc and invokeCalcNamed bind them: by position first, then by name.

func (*Context) InvokeOperationWith

func (ctx *Context) InvokeOperationWith(inst *Instance, name string, args OperationArguments) (map[string]Value, error)

InvokeOperationWith is invokeOperation taking either argument list form.

func (*Context) InvokePredicate added in v0.10.0

func (ctx *Context) InvokePredicate(sym *symbols.Symbol, args []Value, scope *symbols.Scope) (bool, error)

InvokePredicate applies a constraint or requirement to positional arguments and reports whether its conditions hold.

func (*Context) IsVariationFeature

func (ctx *Context) IsVariationFeature(feat *EffectiveFeature) bool

IsVariationFeature reports whether a feature is a variation point, whose feature value holds the variant it is bound to rather than an object of itself.

func (*Context) LiveRoots added in v0.11.0

func (ctx *Context) LiveRoots() []*Instance

LiveRoots returns every object this runtime holds that stands on its own — not held by another's feature value, not materialized only to read a nested declaration, not destroyed — in identity order: rootInstances without its one-object-per-declaration choice, for a sweep that is about each object rather than about a declaration.

func (*Context) MadeElements added in v0.10.0

func (ctx *Context) MadeElements(val Value) ([]int, []Value)

MadeElements is what a collection holds of values already there, each with its 0-based position: every element, but of the required members only those already made.

func (*Context) MaterializationErrors

func (ctx *Context) MaterializationErrors(inst *Instance) (errs []error, bounded bool)

MaterializationErrors reads every feature value of an object, and of the objects its feature values hold, and returns what materializing them reported, in the order the feature values were read. Feature values are lazy, so a default that does not conform to its feature's multiplicity is only found by reading it: a caller reporting on an object it created calls this rather than leaving those diagnostics to whoever reads a feature value next. bounded is true when the walk did not read every feature value — its budget was spent, or nesting it does not descend into was elided — so what it did not reach is unreported rather than clean.

func (*Context) MaxInstances

func (ctx *Context) MaxInstances() int

MaxInstances is the bound SetMaxInstances set, zero when there is none.

func (*Context) MeasurementUnitValue

func (ctx *Context) MeasurementUnitValue(sym *symbols.Symbol) (Value, bool, error)

MeasurementUnitValue is the reference a measurement-unit declaration names (true for one). A library unit is the declaration whatever defines it (`'m/s' = m/s`); a model feature typed by a unit and given a value holds that value instead (false). A measurement scale (`UTC`, `'°C_abs'`) is the one-axis frame its declaration describes.

func (*Context) Model

func (ctx *Context) Model() *Model

Model returns the model-derived part this context runs over.

func (*Context) ModelSeed

func (ctx *Context) ModelSeed() (uint64, bool)

ModelSeed is the seed set by SetModelSeed, and whether one is.

func (*Context) Notes

func (ctx *Context) Notes() []RunNote

Notes returns what the latest run noted about itself, in order: its choice points and the guards it could not evaluate.

func (*Context) ObjectivesOf

func (ctx *Context) ObjectivesOf(sym *symbols.Symbol, scope *symbols.Scope) []Objective

ObjectivesOf returns the objectives sym states, its inherited ones first and in declaration order. An objective restating an inherited one, by name or by redefinition, is the same objective declared again and keeps its place.

func (*Context) ObserveMonteCarlo

func (ctx *Context) ObserveMonteCarlo(sym *symbols.Symbol, args AnalysisArgs, scope *symbols.Scope, self *Instance) (*MonteCarloRun, error)

ObserveMonteCarlo makes one run of a Simulation::MonteCarlo case as RunAnalysis would, reading `observed` and the checks in place of the outputs, which concludeMonteCarlo evaluates.

func (*Context) OccurrenceLife

func (ctx *Context) OccurrenceLife(id int64) (OccurrenceLife, bool)

OccurrenceLife answers the lifetime of the occurrence an instance identity denotes, and false for an identity the context never registered.

func (*Context) OccurrenceUsage

func (ctx *Context) OccurrenceUsage(inst *Instance) string

OccurrenceUsage is the qualified name of the declared usage inst is an occurrence of, or "" for an object materialized any other way.

func (*Context) OptimizationObjectivesOf added in v0.11.0

func (ctx *Context) OptimizationObjectivesOf(sym *symbols.Symbol, scope *symbols.Scope) []Objective

OptimizationObjectivesOf returns the objectives of every stage, in stage order.

func (*Context) OptimizationStagesOf added in v0.11.0

func (ctx *Context) OptimizationStagesOf(sym *symbols.Symbol, scope *symbols.Scope) []OptimizationStage

OptimizationStagesOf returns the stages of sym's optimization: the case's own objectives and conditions, then each nested analysis's, each stage refining the optimum the stages before it settled within its own conditions too.

func (*Context) OrderDependent added in v0.11.0

func (ctx *Context) OrderDependent(feature string) int

OrderDependent reports how many unresolved choice points of the run the feature's value stands on, by its name alone or as the last segment of a written path: those whose alternatives touched it and those what was computed into it stood on (order_marks.go).

func (*Context) OrderDependentAmong added in v0.11.0

func (ctx *Context) OrderDependentAmong(names []string) map[string]int

OrderDependentAmong is, for each named value an unresolved choice point of the run touches, how many do; a value nothing order-dependent wrote is absent.

func (*Context) Parameters added in v0.11.0

func (ctx *Context) Parameters(sym *symbols.Symbol) ([]Parameter, error)

Parameters are the input parameters the calc or case declares, the subject included, in declaration order.

func (*Context) PendingMessages

func (ctx *Context) PendingMessages() []Message

PendingMessages returns the messages still in flight, oldest first.

func (*Context) PerformedExecutor added in v0.11.0

func (ctx *Context) PerformedExecutor(behavior *ObjectBehavior) (*ActionExecutor, error)

PerformedExecutor is the executor of an action the object performs; one a succession order holds back is started once the order admits it, as stateRunFor starts a held machine.

func (*Context) PositiveScalar added in v0.11.0

func (ctx *Context) PositiveScalar(typ *symbols.Symbol) bool

PositiveScalar reports a type that is, or specializes, ScalarValues::Positive.

func (*Context) PostMessage

func (ctx *Context) PostMessage(msg Message)

PostMessage puts a message on the context-wide bus, where every executor sharing this context can see it. Actions and state machines communicate through this bus rather than through per-executor queues, so a message a state machine's entry action sends can be accepted by one of its transitions.

A message posted with a destination but no Delivery — one injected from outside the model — is held to the destination it names.

func (*Context) Pristine

func (ctx *Context) Pristine(inst *Instance) error

Pristine reports whether inst is as its declaration materializes it in a fresh context: nothing written, no behavior moved nor waiting on a clock past zero, no message awaiting it or open to it, not destroyed. Else a heldStateError names the reason.

func (*Context) QualifiedName added in v0.11.0

func (ctx *Context) QualifiedName(sym *symbols.Symbol) string

QualifiedName renders a symbol's qualified name, falling back to its local name when no index is reachable.

func (*Context) QuantityNumber added in v0.11.0

func (ctx *Context) QuantityNumber(typ *symbols.Symbol) (*symbols.Symbol, bool)

QuantityNumber is the feature holding a scalar quantity type's magnitude, the `num` a quantity value's number is bound to; false for any other type.

func (*Context) ReadInSatisfaction added in v0.9.2

func (ctx *Context) ReadInSatisfaction(a *SatisfyAssertion, subject *Instance, scope *symbols.Scope, ref ast.Node) (Value, error)

ReadInSatisfaction evaluates ref, written in scope, as a's require conditions read it on subject: with the requirement's subject and other members bound as checkSatisfactionOn binds them.

func (*Context) RequireAnalysisCase

func (ctx *Context) RequireAnalysisCase(sym *symbols.Symbol) error

RequireAnalysisCase reports ErrNotAnAnalysis for a symbol that is not a case whose body runs — an analysis or verification case definition or usage — describing what it is instead.

func (*Context) RequireMonteCarloCase

func (ctx *Context) RequireMonteCarloCase(sym *symbols.Symbol) error

RequireMonteCarloCase reports errNotMonteCarlo for a symbol that is not an analysis case specializing Simulation::MonteCarlo, describing what it is instead.

func (*Context) Reschedule

func (ctx *Context) Reschedule(policy SchedulePolicy) error

Reschedule is SetSchedule reaching the runs driven call by call as well — the clock and the behaviors the objects run — which resolve their choice points under the policy from their next step on, as a run started under it would from its first: their configurations, pending events, clock and choices so far are kept, and the draws of a seeded policy start over. It fails with ErrRescheduleMidRun from inside a step.

func (*Context) Resolver

func (ctx *Context) Resolver() *resolve.Resolver

Resolver returns the name resolver this context resolves references with.

func (*Context) RunAnalysis

func (ctx *Context) RunAnalysis(sym *symbols.Symbol, args AnalysisArgs, scope *symbols.Scope, self *Instance) (AnalysisResult, error)

RunAnalysis runs an analysis case — a definition or a usage — binding its subject and input parameters from args and its own declarations, and reports every output it declares together with the verdict of each objective and assertion. self, when non-null, is the object a usage is a feature of. A usage run with no arguments answers from the same evaluation a read of its outputs does, so both report the same values. A run whose output could not be evaluated fails, and reports beside the error what it did establish: the evaluations it made and the verdicts, undecided where they read that output.

func (*Context) RunVerification

func (ctx *Context) RunVerification(sym *symbols.Symbol, args AnalysisArgs, scope *symbols.Scope, self *Instance) (VerificationResult, error)

RunVerification runs a verification case's body as RunAnalysis runs an analysis case's — same lowering, same subject and input binding, same step execution — and reports the verdict the body produced together with the objective and assertion verdicts of the same run.

A body that cannot run is the case's error verdict carrying the message, not an error of the call: a verdict is what a verification case answers. An error is returned only for a request that cannot be made at all — a symbol that is not a verification case, or arguments the case does not take.

func (*Context) SatisfactionSubjects added in v0.11.0

func (ctx *Context) SatisfactionSubjects(a *SatisfyAssertion, roots []*Instance) []SatisfactionSubject

SatisfactionSubjects returns the objects an assertion naming no `by` subject is about among roots, the objects the caller holds: every one of the type stating it — each object of a declaration instantiated more than once, the ones nested in a root, and ones classified by the type since they were made — as ValidateObject applies a type's `satisfy r;` to every object of the type. It is nil for an assertion naming its subject, or stated by no type.

func (*Context) SatisfyAssertionOf

func (ctx *Context) SatisfyAssertionOf(sym *symbols.Symbol) (*SatisfyAssertion, error)

SatisfyAssertionOf returns the assertion sym declares, or an error when sym is not a satisfaction assertion. It names the one a `satisfy requirement r by p` form declares under a name.

func (*Context) SatisfyAssertionsIn

func (ctx *Context) SatisfyAssertionsIn(scope *symbols.Scope) []*SatisfyAssertion

SatisfyAssertionsIn returns the satisfaction assertions stated in scope and, recursively, in the scopes nested within it, in declaration order. An assertion is anonymous in its usual form, so it is reached through the element that states it rather than by name.

func (*Context) SatisfySubject

func (ctx *Context) SatisfySubject(a *SatisfyAssertion) (*Instance, error)

SatisfySubject returns an object of the feature a satisfaction assertion names with `by`: the object its requirement is evaluated against when the caller supplies none. A plain name is instantiated afresh; a feature chain is read as the expression it is, so `config.child` materializes the occurrence `config` and answers the object its `child` holds. An assertion naming no subject is about the objects of the type stating it: one stated by a usage instantiates that usage, while one stated by a definition is about whichever objects of it exist (SatisfactionSubjects), so none is made up here.

func (*Context) Schedule

func (ctx *Context) Schedule() SchedulePolicy

Schedule returns the policy the next run resolves its choice points under.

func (*Context) Semantics

func (ctx *Context) Semantics() *semantics.Model

Semantics returns the semantic model this context operates over.

func (*Context) SetBudgets

func (ctx *Context) SetBudgets(b Budgets) error

SetBudgets replaces the bounds this context runs under, rejecting a set that holds a non-positive bound. The evaluation step counter already spent is left alone: the budget is a bound on the run, not a reset of it.

func (*Context) SetCalcCompile

func (ctx *Context) SetCalcCompile(on bool)

SetCalcCompile turns the compiled tier on or off for this context.

func (*Context) SetClockStep

func (ctx *Context) SetClockStep(step float64) error

SetClockStep makes the waits set from now on come due at multiples of step seconds, as a simulation clock ticking by step does: a wait ending between two ticks comes due at the later. 0 restores the continuous clock.

func (*Context) SetDrawPolicy

func (ctx *Context) SetDrawPolicy(policy DrawPolicy)

SetDrawPolicy fixes how the runs started from now on resolve their random draws; a run under way, paused or not, keeps the policy it started under.

func (*Context) SetInterrupt added in v0.10.0

func (ctx *Context) SetInterrupt(flag *atomic.Bool)

SetInterrupt installs the flag that stops this context's runs: once it is raised, the next evaluation step, action step or state machine unit fails with ErrInterrupted. The flag is shared, and the driver lowers it again.

func (*Context) SetMaxInstances

func (ctx *Context) SetMaxInstances(n int)

SetMaxInstances bounds the objects this context holds at once, nested ones counted, zero lifting it; the materialization past it is ErrInstanceLimitExceeded.

func (*Context) SetModelSeed

func (ctx *Context) SetModelSeed(seed uint64)

SetModelSeed fixes the seed the modeled draws of the runs started from now on come from, independent of the scheduling policy; ClearModelSeed unsets it.

func (*Context) SetSchedule

func (ctx *Context) SetSchedule(policy SchedulePolicy) error

SetSchedule sets the policy the runs started from now on resolve their choice points under; a run already under way keeps the one it started with. An `explore` policy is ErrExploreUndriven: it is driven by Explore. A `replay` policy starts its witness over, which the runs then follow in turn.

func (*Context) SetToolRunner

func (ctx *Context) SetToolRunner(runner ToolRunner)

SetToolRunner attaches the runner tool-computed actions and calcs of this context's runs invoke.

func (*Context) SetTrace

func (ctx *Context) SetTrace(tr *TraceRecorder)

SetTrace attaches a trace recorder to this context, so that every expression and calc evaluated through it is recorded. Pass nil to stop tracing.

func (*Context) ShapesOf

func (ctx *Context) ShapesOf(obj *Instance) *Shapes

ShapesOf records the shapes obj and everything it holds were materialized against: the objects reachable through its feature values and connector ends, plus the variants its values selected. A connector no name reaches is materialized again rather than carried, so it is no part of this.

func (*Context) ShapesOfType

func (ctx *Context) ShapesOfType(sym *symbols.Symbol) *Shapes

ShapesOfType records the shape of one declaration as this context resolves it, which is what state held over a declaration rather than an object — a debugging session over an action — is invalidated by a change to.

func (*Context) ShareVerdicts added in v0.9.2

func (ctx *Context) ShareVerdicts() (done func())

ShareVerdicts opens a span over which checks on objects of one shape share their verdicts; the function returned closes it. A span opened within another continues it.

func (*Context) SignalMessage

func (ctx *Context) SignalMessage(signal *symbols.Symbol, args map[string]Value, to *Instance) (Message, error)

SignalMessage builds the message `send Signal(args) to <object>` posts, for PostMessage; a nil object is one anyone may take, an argument no feature of the signal admits is refused. An element that is no signal definition (see SignalDefinitionKinds) is refused with errNotASignal.

func (*Context) Snapshot

func (ctx *Context) Snapshot() (*Snapshot, error)

Snapshot captures the run-derived state of the context between steps: its objects and their values, the bus, the clock, its run bookkeeping and the state of every behavior an object of it runs. An executor driven over the context is captured through its own Snapshot. It fails with ErrSnapshotMidRun from inside a step; a body paused mid-statement is captured where it paused.

func (*Context) SourceLocation

func (ctx *Context) SourceLocation(file string, span source.Span) string

SourceLocation renders where a span in a file was written, as `file:line:col`, falling back to a byte offset for a file whose text was not registered.

func (*Context) StartActionPerformedBy added in v0.11.0

func (ctx *Context) StartActionPerformedBy(action *symbols.Symbol, self *Instance, inputs map[string]Value) (exec *ActionExecutor, reused bool, err error)

StartActionPerformedBy is CreateActionExecutorWithInputs binding to the performance self already runs of the action as performanceOf does; reused marks it, not the caller's to release.

func (*Context) StartStatePerformedBy added in v0.11.0

func (ctx *Context) StartStatePerformedBy(stateMachine *symbols.Symbol, self *Instance) (exec *StateExecutor, reused bool, err error)

StartStatePerformedBy is CreateStateExecutorFor binding to the machine self already exhibits as stateRunFor does; reused marks it, not the caller's to release.

func (*Context) StateOutcomePerformedBy

func (ctx *Context) StateOutcomePerformedBy(stateMachine *symbols.Symbol, self *Instance, events []string) (Outcome, error)

StateOutcomePerformedBy runs a state machine as ExecuteStatePerformedBy does and reports the outcome an exploration compares: its own and, under `this.`, the performer's attributes.

func (*Context) StateOutcomeWithEvents

func (ctx *Context) StateOutcomeWithEvents(stateMachine *symbols.Symbol, events []string) (Outcome, error)

StateOutcomeWithEvents runs a state machine as ExecuteStateWithEvents does and reports where it came to as the outcome an exploration compares.

func (*Context) SubjectMembersOf added in v0.11.0

func (ctx *Context) SubjectMembersOf(requirement *symbols.Symbol) []*symbols.Symbol

SubjectMembersOf are the subject members requirement declares or inherits: what a satisfaction binds to the object `by` names.

func (*Context) SubsettingFeatures

func (ctx *Context) SubsettingFeatures(inst *Instance, typ *symbols.Symbol, name string) []EffectiveFeature

SubsettingFeatures returns the features of typ subsetting the named feature under any of its redefinition names, in declaration order, reading nothing; inst is nil for a type alone.

func (*Context) SweepRunBudget

func (ctx *Context) SweepRunBudget() int64

SweepRunBudget is the number of runs one sweep may ask for when none is stated.

func (*Context) ToolRunner

func (ctx *Context) ToolRunner() ToolRunner

ToolRunner is the runner attached, nil when none is.

func (*Context) Trace

func (ctx *Context) Trace() *TraceRecorder

Trace is the recorder attached to this context, nil when not tracing.

func (*Context) Unfollowed

func (ctx *Context) Unfollowed() error

Unfollowed is the first witness move the last run under a `replay` policy could not make — one refused, or one left over when the run ended — as a ReplayError; nil when the run followed its witness whole or ran under another policy.

func (*Context) UnitOf

func (ctx *Context) UnitOf(scope *symbols.Scope, text string) (semantics.Unit, error)

UnitOf reads a unit spelled as expression text in scope, else in the library's SI package, which a nil scope reads alone; the reading is memoized per scope.

func (*Context) UnresolvedChoices added in v0.11.0

func (ctx *Context) UnresolvedChoices() int

UnresolvedChoices counts the run's choice points whose alternatives may not commute: the ones a default run's result stands only up to.

func (*Context) ValidateObject

func (ctx *Context) ValidateObject(root *Instance, scopes []*symbols.Scope) (ValidationReport, error)

ValidateObject checks every assertion about root and the objects it holds: asserted constraints, carried requirements, and satisfactions (in scopes or the types) about them.

func (*Context) VerificationVerdictsIn

func (ctx *Context) VerificationVerdictsIn(scopes []*symbols.Scope, req *symbols.Symbol) []VerificationVerdict

VerificationVerdictsIn runs the verification cases of every scope whose objective verifies req and reports each body and subcase verdict; a case a type owns runs once per object of that type.

func (*Context) VerificationVerdictsOn added in v0.11.0

func (ctx *Context) VerificationVerdictsOn(scopes []*symbols.Scope, req *symbols.Symbol, subject *Instance) []VerificationVerdict

VerificationVerdictsOn is VerificationVerdictsIn for a verdict about subject: a case a type owns runs once on each object of that type subject is or holds, every held one when subject is nil.

func (*Context) VerificationVerdictsOnce added in v0.11.0

func (ctx *Context) VerificationVerdictsOnce(scopes []*symbols.Scope, req *symbols.Symbol, subject *Instance, runs *VerificationRuns) []VerificationVerdict

VerificationVerdictsOnce is VerificationVerdictsOn skipping the runs recorded in runs, and recording the ones it makes; a nil runs records nothing.

func (*Context) VerifiedOutcome

func (ctx *Context) VerifiedOutcome(result AnalysisResult, verdicts []VerificationVerdict) Outcome

VerifiedOutcome is the outcome of a verification case's run: the case's outcome, and what each body answered as a value named by the case that ran.

type CoordinateFrame

type CoordinateFrame struct {
	Decl           *symbols.Symbol           // the usage declaring the frame; nil for one composed by arithmetic
	Type           *symbols.Symbol           // the type the frame is a value of
	Dimensions     []int64                   // `dimensions`: (3) for a 3-D frame, () for a scale
	Axes           []Unit                    // `mRefs`, one per element the dimensions shape
	Transformation *CoordinateTransformation // `transformation`, whose target is this frame; nil for none
	Scale          *MeasurementScale         // what a MeasurementScale adds; nil for a frame
	Object         int64                     // the object the frame was read from; 0 for one composed
	Text           string                    // the frame as written: `spatialCF`, `spatialCF / s`
}

CoordinateFrame is a VectorMeasurementReference held as a value: the axes of a coordinate frame, or the one axis a measurement scale is, with the placement relating it to another reference where the model states one.

func (*CoordinateFrame) Name

func (f *CoordinateFrame) Name() string

Name is how the frame is referred to in diagnostics: its declared name, else how it was composed.

func (*CoordinateFrame) String

func (f *CoordinateFrame) String() string

String renders the frame as its name over its axes: `spatialCF [m, m, m]`; a scale over the unit its magnitudes are in: `°C_abs [°C]`.

type CoordinateTransformation

type CoordinateTransformation struct {
	Decl      *symbols.Symbol  // the usage declaring the transformation; nil for a constructed one
	Type      *symbols.Symbol  // the type the transformation is a value of
	Source    *CoordinateFrame // `source`; nil when the model states none
	Target    *CoordinateFrame // `target`; nil for a frame's own transformation, whose target it is
	Placement *FramePlacement
	Sequence  []FrameStep
	Affine    *AffineTransformation3d
	Object    int64
}

CoordinateTransformation is a CoordinateTransformation held as a value: the placement of the target in the source by at most one of Placement, Sequence and Affine; a subtype of no library shape holds none and cannot be applied.

func (*CoordinateTransformation) Name

func (t *CoordinateTransformation) Name() string

Name is how the transformation is referred to in diagnostics.

func (*CoordinateTransformation) String

func (t *CoordinateTransformation) String() string

String renders the transformation as its name over the frames it relates: `trs (datum → lbcf)`.

type Counted

type Counted struct {
	Count int64
	Value float64
}

Counted is one term of a weighted mean: Value, over Count runs; the count is exact, as the runs a tool summarises are.

type CoverageGap added in v0.11.0

type CoverageGap int

CoverageGap is a construct whose unordered alternatives a run performs in one order without a choice point, so exploring or checking it enumerates fewer orders than the library admits and neither may report its outcome set complete. No construct records one today: every order the executors take without a choice point is fixed by the library or canonical (see scheduling.md). A construct found to perform an open order as one move is named here and recorded with noteGap, so Complete() is false over it rather than a note.

func (CoverageGap) Description added in v0.11.0

func (g CoverageGap) Description() string

Description says what the gap left unenumerated, as a status prints it.

func (CoverageGap) String added in v0.11.0

func (g CoverageGap) String() string

String is the gap's identifier, as a conformance case's `exploreGaps` names it.

type Decision

type Decision struct {
	Fires   []string
	Resumes []string
}

Decision is what dispatching a message now would do: the transitions that would fire on it, or the do behaviors parked at an accept it lets go on.

func (Decision) Enabled

func (d Decision) Enabled() bool

Enabled reports whether dispatching the message would do something with it.

type DeclaredReader

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

DeclaredReader reads feature values as the model declares them for a concrete carrier, materializing each element once and starting no behavior.

func NewDeclaredReader

func NewDeclaredReader(model *semantics.Model, resolver *resolve.Resolver) *DeclaredReader

NewDeclaredReader creates a reader over a fresh, behavior-free runtime context. model carries the checker's argument typing, as NewModel requires: a feature valued by a call is read through it, and fails with errNoArgumentTyper without one.

func NewDeclaredReaderIn added in v0.9.2

func NewDeclaredReaderIn(held *Context) *DeclaredReader

NewDeclaredReaderIn creates a reader on a fresh declarative context seeded from held: its tool runner, so tool-computed calcs a derived feature calls answer through the same runner, the parser reading the units they answer in, the budgets it runs under, and the notes a run makes, which held's own Notes report.

func (*DeclaredReader) CompareMagnitudes

func (r *DeclaredReader) CompareMagnitudes(left, right semantics.Quantity) (int, error)

CompareMagnitudes orders two quantities on the left one's reference, a point on a measurement scale carried through its anchor.

func (*DeclaredReader) QuantityBinary

func (r *DeclaredReader) QuantityBinary(op ast.OperatorKind, left, right semantics.Quantity) (semantics.Quantity, error)

QuantityBinary applies a binary operator to two quantities as evaluation does, the affine cases of a point on a measurement scale included.

func (*DeclaredReader) QuantityUnary

QuantityUnary applies a unary operator to a quantity as evaluation does: a point on a measurement scale (`26.85 [SI::'°C_abs']`) has no negative.

func (*DeclaredReader) Read

func (r *DeclaredReader) Read(sym *symbols.Symbol, name string) (Value, error)

Read evaluates the named feature of the element sym denotes, resolving every leaf through that element's redefinitions. An unbound leaf is a *NoValueError.

func (*DeclaredReader) Validate

func (r *DeclaredReader) Validate(sym *symbols.Symbol, scopes []*symbols.Scope) (ValidationReport, error)

Validate checks every assertion about the object the element declares, and the objects it holds, as the model declares them: ErrNotAnObject for an element with no object (a package, an attribute).

func (*DeclaredReader) VerificationVerdictsIn

func (r *DeclaredReader) VerificationVerdictsIn(scopes []*symbols.Scope, req *symbols.Symbol) []VerificationVerdict

VerificationVerdictsIn runs the verification cases in scopes whose objective verifies req, in the reader's behavior-free context.

type DeliveryKind

type DeliveryKind uint8

DeliveryKind is what a message's destination resolved to, and so what a consumer must match: an unaddressed message resolved nothing and any consumer may take it, while every addressed or routed one names a destination in full.

type Dispatch

type Dispatch struct {
	Event   Event
	Fired   bool
	Resumed []string
}

Dispatch is what became of an event a step took off the queue: a transition fired on it, or nothing was enabled for it and it was dropped; Resumed names the states whose do behavior went on from an accept with it.

type Distribution

type Distribution struct {
	Count    int
	Integral bool
	Min      semantics.Value
	Mean     float64
	// Deviation is the sample standard deviation about Mean, 0 for fewer than two runs.
	Deviation float64
	Max       semantics.Value
	P50       semantics.Value
	P90       semantics.Value
	Histogram []HistogramBin
}

Distribution summarises one observable over the runs of a Monte Carlo: extremes, mean, sample standard deviation, nearest-rank p50/p90 and a histogram, exact on Integers save the Real mean and deviation.

func Distribute

func Distribute(numbers []semantics.Value) *Distribution

Distribute summarises numbers in any order, nil for none: all Integers make an integral distribution computed exactly, a Real among them one over Reals.

type Divergence

type Divergence struct {
	Feature string
	Values  []DivergentValue
}

Divergence is a feature whose final value the schedule decides: every value some complete schedule leaves it with, in canonical order.

func (Divergence) String

func (d Divergence) String() string

String spells the divergence as `x ends as 1 or 2`.

type DivergentValue

type DivergentValue struct {
	Value   string
	Witness Witness
}

DivergentValue is one final value of a divergent feature and a schedule reaching it.

type DrawPolicy

type DrawPolicy int

DrawPolicy is how a run resolves the draws of the RandomFunctions library: at random from the seeded stream, or at a fixed point of each call's distribution. weighted decisions are not durations, so they draw the same under every policy.

const (
	// DrawRandom draws from the seeded modeled stream, or a witness's recorded draws.
	DrawRandom DrawPolicy = iota
	// DrawMin yields the least value each call can draw.
	DrawMin
	// DrawMax yields the greatest value each call can draw.
	DrawMax
	// DrawAverage yields the mean of each call's distribution.
	DrawAverage
)

func ParseDrawPolicy

func ParseDrawPolicy(text string) (DrawPolicy, error)

ParseDrawPolicy reads a policy spelling: one of drawPolicyNames.

func (DrawPolicy) Fixed

func (p DrawPolicy) Fixed() bool

Fixed reports whether the policy resolves every draw without a random stream.

func (DrawPolicy) String

func (p DrawPolicy) String() string

String is the policy's spelling, as ParseDrawPolicy reads it.

type DrawTaken

type DrawTaken struct {
	What  string
	Value semantics.Value
}

DrawTaken is one random value a run drew: the call that drew it with its arguments as evaluated, and the value, spelt `draw uniform(1, 80) = 42.5`.

func ParseDraw

func ParseDraw(text string) (DrawTaken, error)

ParseDraw reads one draw as DrawTaken.String spells it: `draw <call> = <number>`.

func (DrawTaken) Describe

func (d DrawTaken) Describe() string

Describe renders the draw for a diagnostic.

func (DrawTaken) String

func (d DrawTaken) String() string

String spells the draw as a witness lists it and ParseDraw reads it back.

type EffectiveFeature

type EffectiveFeature struct {
	Name         string
	Symbol       *symbols.Symbol // the declaring feature symbol
	OwnerType    *symbols.Symbol // type that declares this feature (may be supertype)
	Type         *symbols.Symbol // resolved type (nil if untyped)
	Multiplicity semantics.Range // declared or inherited (default 1..1)
	DefaultValue ast.Node        // value-binding expression (nil if none)
	DefaultDecl  *symbols.Symbol // feature the DefaultValue was written on (nil if none)
	HoldsSet     bool            // values form a set: a Collection's unordered unique elements
	Unique       bool            // holds no two equal values (KerML isUnique, the default)
	// GovernedByChain marks a feature a valued nested chain from a more specific
	// body reaches below, so its bound value does not govern, as with a
	// redefining body.
	GovernedByChain bool
}

EffectiveFeature represents one feature value in a type's flattened schema: own + inherited − redefined/masked, carrying type + multiplicity + default.

func (*EffectiveFeature) DeclScope

func (f *EffectiveFeature) DeclScope() *symbols.Scope

DeclScope returns the scope the feature was declared in, which is the scope a default value written on it must be evaluated in: an inherited feature's default refers to names visible where the supertype was written, not where the instantiated type is.

func (*EffectiveFeature) DefaultScope

func (f *EffectiveFeature) DefaultScope() *symbols.Scope

DefaultScope returns the scope DefaultValue resolves its names in, which for an inherited default is where the redefined declaration wrote it.

func (*EffectiveFeature) HoldsOnlyContributions

func (f *EffectiveFeature) HoldsOnlyContributions() bool

HoldsOnlyContributions reports whether a feature of known multiplicity materializes no object of its own: it is abstract, or a scalar whose lower bound demands none and whose own body describes none.

func (*EffectiveFeature) Scalar

func (f *EffectiveFeature) Scalar() bool

Scalar reports whether the feature holds at most one value.

type EvalContext

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

EvalContext is the lexical environment during evaluation (Tier 3).

func NewEvalContextIn

func NewEvalContextIn(ctx *Context, scope *symbols.Scope, self *Instance) *EvalContext

NewEvalContextIn creates an evaluation context bound to an instance, so that a feature name resolves to that instance's feature value rather than to the declared default of the same name.

func (*EvalContext) Eval

func (ec *EvalContext) Eval(node ast.Node) (Value, error)

Eval evaluates an expression node. Returns a Value or an error. Increments the run's steps on each eval call; errors when they are >= ctx.maxSteps. When the context is traced, the evaluation is recorded after its sub-expressions, which makes sub-expression order part of the trace.

func (*EvalContext) Lookup

func (ec *EvalContext) Lookup(name string) (Value, bool, error)

Lookup searches for a name in the frame stack (innermost first).

func (*EvalContext) Pop

func (ec *EvalContext) Pop()

Pop removes the top frame from the stack (on return, lambda exit).

func (*EvalContext) Push

func (ec *EvalContext) Push(bindings map[string]Value)

Push adds a new frame to the stack (on calc invocation, lambda entry).

type Event

type Event struct {
	ID        int64       // Unique event ID
	Type      EventType   // Event type
	Timestamp float64     // Virtual time when event fires
	Payload   interface{} // Event-specific data
}

Event represents a state machine event.

func (Event) String

func (e Event) String() string

type EventQueue

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

EventQueue is a priority queue of events sorted by timestamp (min-heap).

func (*EventQueue) Events

func (q *EventQueue) Events() []Event

Events lists the pending events in dispatch order.

func (*EventQueue) Len

func (q *EventQueue) Len() int

Len returns the number of pending events.

func (*EventQueue) Peek

func (q *EventQueue) Peek() Event

Peek returns the earliest event without removing it.

func (*EventQueue) Pop

func (q *EventQueue) Pop() Event

Pop removes and returns the earliest event.

func (*EventQueue) Push

func (q *EventQueue) Push(e Event)

Push adds an event to the queue.

func (*EventQueue) With

func (q *EventQueue) With(e Event) *EventQueue

With is a copy of the queue with the event pushed; the queue itself is untouched.

type EventType

type EventType int

EventType identifies event kinds for state machines.

func (EventType) String

func (t EventType) String() string

type ExecutionState

type ExecutionState int

ExecutionState tracks executor state.

const (
	StateReady      ExecutionState = iota // Not started
	StateRunning                          // In progress
	StateCompleted                        // Reached terminal state
	StateSuspended                        // Paused for debugging
	StateWaiting                          // Every remaining token is parked at an accept
	StateTerminated                       // Ended by a terminate before reaching a terminal state
)

func (ExecutionState) Ended

func (s ExecutionState) Ended() bool

Ended reports an execution over for good: completed, or ended by a terminate.

func (ExecutionState) String

func (s ExecutionState) String() string

type Exploration

type Exploration struct {
	Budget   ExploreBudget
	Runs     int
	Outcomes []ExploredOutcome
	// BudgetsHit names the budgets the exploration ran into, `runs` before
	// `depth`; none when it is complete.
	BudgetsHit []string
	// Unenumerated are the constructs whose unordered alternatives the runs took
	// in one order without a choice point, so fewer orders were run than the
	// library admits; none when the exploration is complete.
	Unenumerated []CoverageGap
	// Scope is the distinct reasons the runs' outcomes were observed short of quiescence.
	Scope []ObservationReason
	// contains filtered or unexported fields
}

Exploration is what exploring a behavior found: its distinct outcomes, in canonical order, and whether every linearization within the budget was run.

func Explore

func Explore(stop context.Context, policy SchedulePolicy, fresh func() (*Context, error), run func(*Context) (Outcome, error)) (*Exploration, error)

Explore runs a behavior once per linearization within the policy's budget, one run at a time in plan order. A run that fails after it begins is an outcome; setup failures and a caller that goes away fail the exploration.

func ExploreWith

func ExploreWith(stop context.Context, policy SchedulePolicy, jobs int, fresh func(job int) (*Context, error), run func(*Context) (Outcome, error)) (*Exploration, error)

ExploreWith explores as Explore does with up to jobs runs going concurrently, fresh building each run's context for the job making it; the result does not depend on jobs.

The prefixes form a work queue in plan order, the order one job visits them, and the runs budget is a cut in that order. Plan order is by departures first — every prefix departing from the first run at one choice before any departing at two — so a budget of one more run than the first run's choice points varies each of them at least once, then by the position of the choice varied, earliest first. A run is committed once every prefix before it has completed; one started earlier is speculative, and at most jobs of those are discarded in all. The queue never holds more than runs prefixes, so no more than runs jobs are ever put to work.

func (*Exploration) Complete

func (x *Exploration) Complete() bool

Complete reports whether every linearization the library admits was run: no budget stopped the exploration and no construct was left unenumerated.

func (*Exploration) FailedLinearizations added in v0.10.0

func (x *Exploration) FailedLinearizations() int

FailedLinearizations counts the runs whose outcomes carry runtime errors.

func (*Exploration) ProbabilitiesBounded

func (x *Exploration) ProbabilitiesBounded() bool

ProbabilitiesBounded reports whether the outcomes' probabilities are lower bounds while weighted probabilities have unexplored linearizations.

func (*Exploration) Status

func (x *Exploration) Status() string

Status renders how the exploration ended: `complete (N runs)`, or which budget was hit after how many runs and what was left unenumerated.

func (*Exploration) Weighted added in v0.10.0

func (x *Exploration) Weighted() bool

Weighted reports whether a committed run made a weighted choice.

type ExploreBudget

type ExploreBudget struct {
	Runs  int
	Depth int
}

ExploreBudget bounds an exploration: how many runs it may make and how many choice points one run may resolve before the rest take their first alternative.

type ExploredOutcome

type ExploredOutcome struct {
	Outcome        Outcome
	Linearizations int
	// Probability is nil unless the exploration made a weighted choice.
	Probability *ProbabilityRange
	Witness     []ChoiceTaken
	// WitnessRun is the 1-based number of the run the witness is.
	WitnessRun int
}

ExploredOutcome is one distinct outcome an exploration reached: how many linearizations reached it, its model probability range when weighted, and the choices of the first run that did.

type ExpressionParser

type ExpressionParser func(origin, text string) (ast.Node, bool)

ExpressionParser parses text, read from origin, as exactly one expression; false for anything else. The caller that builds a Model supplies it; the runtime parses nothing itself.

type FeatureOwner

type FeatureOwner int

FeatureOwner tells whose feature a name a check compares resolves to.

const (

	// OwnedByPerformer: `this.<name>`, a feature of the object performing the action.
	OwnedByPerformer FeatureOwner
	// OwnedByNode: `node.path`, a feature a performance of one of the action's nodes holds.
	OwnedByNode
)

type FeatureValue

type FeatureValue struct {
	Feature *EffectiveFeature

	Value          Value // scalar feature value (multiplicity [1])
	Values         Value // collection feature value (Sequence or Set)
	Materialized   bool  // lazy flag: has this feature value been instantiated?
	Written        bool  // a run assigned this value, so no default derives it again
	BindingDerived bool  // value came from binding propagation rather than a write
	// Assumed marks a value fixed by nothing but the feature's multiplicity: its
	// minimum materialized, or contributions short of its maximum.
	Assumed bool
	// contains filtered or unexported fields
}

Feature value holds the runtime value(s) for one feature.

func (*FeatureValue) HeldValue

func (s *FeatureValue) HeldValue() Value

HeldValue is the value the feature value reads as: its collection when the feature is multi-valued, otherwise its scalar.

func (*FeatureValue) ReadValue

func (s *FeatureValue) ReadValue(name string) (Value, error)

ReadValue is what the feature value reads as in an expression: what it holds, or the empty sequence when it holds nothing and its multiplicity admits that. A required feature holding nothing is uninitialized.

type FeatureValueError

type FeatureValueError struct {
	Err error
	// Instance holds the feature value that did not materialize, as the feature named Feature.
	Instance *Instance
	Feature  string
}

FeatureValueError marks a feature value that could not be materialized. It reads as the error that kept the feature value from materializing and unwraps to it as well as to ErrFeatureValueMaterialization, so a caller tests either.

func (*FeatureValueError) Error

func (e *FeatureValueError) Error() string

func (*FeatureValueError) Unwrap

func (e *FeatureValueError) Unwrap() []error

type FiredTransition

type FiredTransition struct {
	Decl   ast.Node
	Source ast.Node
	Target ast.Node
	Owner  ast.Node
}

FiredTransition is one transition taken: where it was written and the vertices it joined. An entry transition has no Source; it leaves the start of Owner's body, the one keying it in the graph's EntryTransitions (nil: the machine's own).

type FramePlacement

type FramePlacement struct {
	Origin          Value   // a vector quantity, or a scalar quantity for a one-dimensional frame
	BasisDirections []Value // vector quantities, one per target axis
}

FramePlacement is a CoordinateFramePlacement: the target frame's origin as a vector in the source frame, and its basis directions there; none for the source's own orientation.

type FrameStep

type FrameStep struct {
	Translation *Value    // Translation::translationVector, a vector quantity
	Axis        *Value    // Rotation::axisDirection, a vector quantity
	Angle       *Quantity // Rotation::angle, an angular measure
	Intrinsic   bool      // Rotation::isIntrinsic
	Object      int64
}

FrameStep is one TranslationOrRotation of a TranslationRotationSequence.

type Held

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

Held is a copy of what a performance holds at one moment: the features it holds, and their values looked up under the names the performance keys them by.

func (Held) Features

func (h Held) Features() []lower.Attribute

Features are the attributes and parameters the performance holds, the graph's own then the inherited ones it does not redefine, as the run initializes them.

func (Held) Unbound

func (h Held) Unbound() []lower.Attribute

Unbound lists the inputs the performance holds no value for: the features it reads rather than writes back, declared with no default and bound by nothing. One marked Optional may also hold no value at all, which the run reads as the empty sequence, so absence is among the states it ranges over.

func (Held) Value

func (h Held) Value(name string) (Value, bool)

Value is the value held under name: its redefinition's when name is redefined.

type HeldFeature added in v0.11.0

type HeldFeature struct {
	Feature   EffectiveFeature
	Composite *symbols.Symbol
	Variants  []*symbols.Symbol
}

HeldFeature is an object-holding feature the model declares on an element, with what else may state assertions its objects carry: the feature's composite type, and the variants of the feature or of that type, each applying only to an object of the variant the feature selects.

type HeldImage

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

HeldImage is a closure of held objects by value — objects, lifetimes, executions, messages in flight — that materializes into other contexts under the same identities (see Image).

func (*HeldImage) Holds

func (img *HeldImage) Holds(id int64) bool

Holds reports whether the image holds an object under id.

func (*HeldImage) Materialize

func (img *HeldImage) Materialize(dst *Context) error

Materialize gives dst objects of its own for the image under the same identities, advancing dst's sequence past them and past the identities set aside for connectors not materialized yet; errImageIdentityTaken and errImageClock refuse, leaving dst as it was.

type HeldImageError

type HeldImageError struct {
	ID   int64
	Type *symbols.Symbol
	What string
	Err  error
}

HeldImageError reports what of an object kept an image from being taken or materialized: the object, and the typed reason.

func (*HeldImageError) Error

func (e *HeldImageError) Error() string

Error names what was being done to the object and the reason it could not be.

func (*HeldImageError) Unwrap

func (e *HeldImageError) Unwrap() error

Unwrap exposes the typed reason.

type HeldObjectsError

type HeldObjectsError struct {
	Feature string
	Err     error
}

HeldObjectsError reports the feature HeldObjects could not read, and why.

func (*HeldObjectsError) Error

func (e *HeldObjectsError) Error() string

func (*HeldObjectsError) Unwrap

func (e *HeldObjectsError) Unwrap() error

type HistogramBin

type HistogramBin struct {
	Lo, Hi semantics.Value
	Count  int
}

HistogramBin is one bin of a histogram and how many runs fell in it: the numbers from Lo up to Hi, Hi included in the last bin and in every bin of an integral distribution.

type Horizon

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

Horizon is the instant a check runs the clock to: the zero Horizon is none, and one at t=0 dispatches what is due at the start alone.

func HorizonAt

func HorizonAt(t float64) Horizon

HorizonAt is the horizon at instant t.

func HorizonInitial added in v0.10.0

func HorizonInitial() Horizon

HorizonInitial is the horizon of machines run without a duration: each takes its initial transition only, as a run of a state machine with no `-advance` does.

func (Horizon) Bound added in v0.11.0

func (h Horizon) Bound() (at float64, ok bool)

bound is the instant the horizon stops the clock at, false for none.

type InputBinding

type InputBinding struct {
	Name  string
	Value Value
}

InputBinding is the value one input parameter of a case was bound to for a run: its argument, or the default its declaration evaluated to.

type InputTaken

type InputTaken struct {
	Feature string
	// Value is the value, when the witness was made in memory; ValInvalid for one
	// read from a file, whose Written is evaluated where the action's defaults are.
	Value Value
	// Written is the value as the notation spells it: what a witness file holds.
	Written string
}

InputTaken is one input a witness fixes before the run's first move: a feature of the action or its performer and its value, spelt `input <feature> = <value>`.

func InputOf

func InputOf(feature string, value Value) InputTaken

InputOf is the input fixing feature at value, spelt as the value formats.

func (InputTaken) String

func (in InputTaken) String() string

String spells the input as a witness lists it and parseInput reads it back.

type Instance

type Instance struct {
	ID            int64                    // unique identity
	Type          *symbols.Symbol          // the def/usage symbol this instantiates
	FeatureValues map[string]*FeatureValue // feature name → feature value

	// Ends are the ends of the connector this object materializes, in declaration
	// order, and nil for an object that is no connector. A named end also reads
	// through the feature value of that name; the order is what an end with no name of its
	// own is identified by.
	Ends []ConnectorEnd
	// contains filtered or unexported fields
}

Instance is a runtime-materialized object (Tier 2).

func (*Instance) Behaviors

func (inst *Instance) Behaviors() []*ObjectBehavior

Behaviors are the behaviors the object runs, in declaration order.

func (*Instance) BindFeatureValue added in v0.10.0

func (inst *Instance) BindFeatureValue(ctx *Context, name string, value Value) error

BindFeatureValue writes a value to the named feature value of the object as the model determines it rather than as a behavior changes it: the object's initial values, the seeding of a performance occurrence with what its run already holds, a parameter bound at a call, a binding's other end, a message's payload. It answers to the declaration as SetFeatureValue does, but a constant or derived feature is not refused, since that is how such a feature gets its values.

func (*Instance) ExhibitedState

func (inst *Instance) ExhibitedState() (*ObjectBehavior, bool)

ExhibitedState returns the machine the object exhibits, and false when it exhibits none. With several, it returns the first declared.

func (*Instance) ExhibitedStates

func (inst *Instance) ExhibitedStates() []*ObjectBehavior

ExhibitedStates returns every machine the object exhibits, in declaration order.

func (*Instance) ExhibitedStatesOf

func (inst *Instance) ExhibitedStatesOf(sym *symbols.Symbol) []*ObjectBehavior

ExhibitedStatesOf returns the machines the object exhibits under sym's declaration: the one sym itself binds, or else every one reaching sym through its bindings (the usage it names, or the definition holding its body) or typed by it, since one definition can be the body or the kind of several exhibited usages. Declarations are compared.

func (*Instance) GetFeatureValue

func (inst *Instance) GetFeatureValue(ctx *Context, name string) (*FeatureValue, error)

GetFeatureValue retrieves the feature value for the named feature, materializing it lazily if it's a composite feature that hasn't been accessed yet. A feature value that could not be materialized is marked as such — it unwraps to ErrFeatureValueMaterialization — so a caller can tell it from any other failure to evaluate, whatever the expression it surfaced through.

func (*Instance) HeldUnder

func (inst *Instance) HeldUnder() *symbols.Symbol

HeldUnder returns the usage an object's owner holds it as (`Car::wheels` for `car.wheels[2]`), or nil for an object held by none.

func (*Instance) KeptConnectorIDs

func (inst *Instance) KeptConnectorIDs() []int64

KeptConnectorIDs returns the identities of the connectors a carry-over set aside for the instance to materialize again, anonymous and named, ascending.

func (*Instance) MaterializedConnectors

func (inst *Instance) MaterializedConnectors(ctx *Context) []*Instance

MaterializedConnectors returns the anonymous connectors the instance has already materialized, none when they were never asked for; it materializes nothing.

func (*Instance) MemberValue added in v0.11.0

func (inst *Instance) MemberValue(ctx *Context, name string) (*FeatureValue, error)

MemberValue reads the member of the object that name denotes, as every surface reads one: a feature value of its shape, else a member the shape leaves out through kernelMemberRead. GetFeatureValue alone probes the shape.

func (*Instance) OwnedConnectors

func (inst *Instance) OwnedConnectors(ctx *Context) ([]*Instance, error)

OwnedConnectors returns the connectors the instance owns that no feature names — an anonymous `connect a.p to b.q` member — materializing each once, in declaration order. A named connector is reached through its feature value instead.

func (*Instance) Owner

func (inst *Instance) Owner() (*Instance, string)

Owner answers the object holding this one and the feature of it that does, or nil and "" for an object no other holds.

func (*Instance) PerformedActionsOf

func (inst *Instance) PerformedActionsOf(sym *symbols.Symbol) []*ObjectBehavior

PerformedActionsOf returns the actions the object performs under sym's declaration, matched as ExhibitedStatesOf matches machines.

func (*Instance) RestoreConnector

func (inst *Instance) RestoreConnector(ctx *Context, id int64) (*Instance, error)

RestoreConnector materializes again the connector a carry-over set aside under id, which takes that identity back; nil when the instance kept no such identity. A connector returned along with an error is kept: an older behavior failed answering it.

func (*Instance) SetFeatureValue

func (inst *Instance) SetFeatureValue(ctx *Context, name string, value Value) error

SetFeatureValue writes a value to the named feature value of the object, which is how a behavior the object performs updates the object's own state. The value must conform to the multiplicity governing the feature; a feature the object does not have is reported rather than added. A feature declared `constant` or `derived`, or redefining or subsetting one that is, is refused as errReadOnlyFeature and keeps what it held: a constant feature does not change over the lifetime of its featuring occurrence, and a derived one has the values the model determines (KerML 1.0 §8.3.3.3.4, Feature::isConstant and Feature::isDerived).

func (*Instance) Types

func (inst *Instance) Types() []*symbols.Symbol

Types returns the types an object has: the one it was materialized from, then the classifiers a behavior has since given it.

type Invocation

type Invocation struct {
	Actions []*ActionExecutor
	States  []*StateExecutor
	// Names are the names the behaviors' observables are reported under in a joint
	// outcome, actions first; the behaviors' own names when absent.
	Names []string
	// PerformerNames spell, beside Names, the object each behavior performs on as the
	// surface named it, "" for none; `object #<id>` when absent.
	PerformerNames []string
	Horizon        Horizon
}

Invocation is what one check searches: the behaviors started on one clock, in the order started, and the horizon the clock runs to. The objects the started behaviors materialize bring their own behaviors onto the clock.

func (*Invocation) Completed

func (inv *Invocation) Completed() bool

Completed reports whether every started action reached its end.

func (*Invocation) Context

func (inv *Invocation) Context() *Context

Context is the context the started behaviors run in, nil for an empty invocation.

func (*Invocation) Outcome

func (inv *Invocation) Outcome() Outcome

Outcome is what the started behaviors came to: one behavior's own outcome, or the joint outcome of several, plus what the performing objects hold (`this.` for one, `<object>.` else).

func (*Invocation) PerformerAttributes added in v0.9.2

func (inv *Invocation) PerformerAttributes() map[string]Value

PerformerAttributes are the attributes the behaviors' performers hold, as an outcome reports them: under `this.` for one performer, under its name for several.

func (*Invocation) Performers

func (inv *Invocation) Performers() []*Instance

Performers lists the distinct objects the started behaviors perform on, in start order.

func (*Invocation) Release

func (inv *Invocation) Release()

Release ends every started executor's run.

type MeasurementRef

type MeasurementRef struct {
	Unit Unit
}

MeasurementRef is a ScalarMeasurementReference held as a value: the Unit a quantity carries (named product = declarations, term = reduction), by itself.

func (*MeasurementRef) Declaration

func (r *MeasurementRef) Declaration() *symbols.Symbol

Declaration is the one unit declaration the reference names at the first power (`SI::m`); nil for a unit composed of several (`m/s`, `m**2`).

func (*MeasurementRef) String

func (r *MeasurementRef) String() string

String renders the reference as a quantity's unit is written: `m`, `km/h`, `m**2`.

type MeasurementScale

type MeasurementScale struct {
	Unit    Unit
	Mapping *QuantityValueMapping
}

MeasurementScale is what a scale states beyond its one axis: the unit a magnitude on it is in, and the point mapping it onto another reference.

type Message

type Message struct {
	// Serial is the bus's number for the message, unique within a context's run; 0 for none.
	Serial     uint64
	SignalType string
	// Signal is the definition SignalType resolved to when the send was built,
	// nil where the message's type is known only as a name. An accept matches it
	// by conformance, so a subtype message satisfies a supertype accept and
	// same-named definitions of different packages stay apart.
	Signal *symbols.Symbol
	// Event is the feature the message was sent from (`send shutDown to x`), nil
	// where none or unresolved; EventName is its written name, the fallback then.
	// EventObject is the occurrence that feature held when sent, or the object
	// performing a behavioral feature (`send alert()`), 0 for none: two parts of
	// one type hold their own occurrences of the one declared event.
	Event       *symbols.Symbol
	EventName   string
	EventObject int64
	Target      string
	Port        string
	Object      int64
	PortID      int64
	Delivery    DeliveryKind
	// TypedByAccept marks a message queued by name alone from outside the model
	// (QueuedEvent.Signal) that names no signal definition where its sender
	// stands: the accept that takes it, matching it by name, types it by the
	// definition the accept's own name denotes in the scope the accept is written
	// in, so that its payload binds as a sent occurrence's does.
	TypedByAccept bool
	// Payload binds features of the message's type by name, as the send's arguments did.
	Payload map[string]Value
	// Value is the one value a send of an expression carries (`send 7`, `send d`),
	// the occurrence `send new T(…)` constructed, or the one an accept built from
	// Payload; nil until any.
	Value *Value
	// contains filtered or unexported fields
}

Message is a signal instance in flight.

SignalType names the message's type: the type the send statement named, or the scalar type of the value it evaluated to. An accept whose parameter is typed consumes only messages of that type, so two sends of different types reach different accepts regardless of the order they were posted in.

Target names the receiving node of the sending behavior a `send m to r` addressed; a consumer accepts a message addressed to itself or to no one.

Port names the port the message reached — the peer end a `via p` send routed to, or the port an addressed send resolved to — and only an accept on that port consumes it, keeping port-routed and addressed traffic separate.

Object identifies the object the message reached, 0 for none, and Delivery what of that destination a consumer must satisfy to take the message.

PortID identifies the port object the message reached, 0 where the run holds none. A binding connector makes a boundary port and an inner port one object, so an accept on either port takes a message that reached the other.

func NamedSignalMessage

func NamedSignalMessage(name string, to *Instance) Message

NamedSignalMessage builds the message a send of a signal no declaration types posts: matched by name alone, addressed to the object when there is one.

type Model

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

Model is the model-derived part of execution: the semantic model and resolver a run reads, and what is memoized from them — calc shapes, write targets, invocation targets, literal values, effective features, the behaviors a type binds — which the model fixes and no run changes. Every context built over one Model reuses it, so a run pays for none of it again; the run-derived state, what a run creates and a snapshot captures, is the Context's.

The memo tables fill lazily into plain maps, as the resolver's and the semantic model's do, so a Model is for one goroutine at a time: one per analysis worker.

func NewModel

func NewModel(sem *semantics.Model, resolver *resolve.Resolver) *Model

NewModel builds the model-derived part of execution over a semantic model and the resolver it resolves names with; either may be nil for a context that evaluates literals alone. The caller installs the checker's argument typing on sem (semantics.Model.SetArgumentTyper) before any call is selected; a run that selects a call without one fails with errNoArgumentTyper. Contexts are built over it with NewContext.

func (*Model) RegisterScope

func (m *Model) RegisterScope(scope *symbols.Scope)

RegisterScope gives the Model a scope tree the caller resolves references in, so a declaration carried over by Adopt is rebound to the symbol that tree declares for it rather than to the index's own.

func (*Model) RegisterSource

func (m *Model) RegisterSource(sf *source.SourceFile)

RegisterSource gives the Model the text of a file it was read from, so an error about a declaration in it reports a line and column.

func (*Model) Resolver

func (m *Model) Resolver() *resolve.Resolver

Resolver returns the name resolver the Model resolves references with.

func (*Model) Semantics

func (m *Model) Semantics() *semantics.Model

Semantics returns the semantic model the Model is derived from.

func (*Model) SetExpressionParser

func (m *Model) SetExpressionParser(parse ExpressionParser)

SetExpressionParser installs the parser the Model reads witness input values and tool units with; units the previous parser read are forgotten, so every lookup goes through it.

func (*Model) Sources

func (m *Model) Sources() []*source.SourceFile

Sources returns the registered files of the model, in name order.

func (*Model) Text

func (m *Model) Text() source.Lookup

Text answers a span in a document from the registered files, falling back to the notation lookup the semantic model reads documentation from.

type MonteCarloRun

type MonteCarloRun struct {

	// Case is the qualified name of the case that ran; Subject the object it ran on.
	Case    string
	Subject *Instance

	// Number is the run's number in its Monte Carlo, the row it was drawn as; a
	// sample names a run by it, whatever earlier runs failed.
	Number int64

	// Observed is the value the run's `observed` came to, null when the run left it unbound.
	Observed Value

	// Inputs are the values the run bound the case's input parameters to, in
	// declaration order. Outputs are every declared output of this iteration
	// as the iteration established it — the sample's statistics excluded — with
	// the observed feature appended when it declares no output of its own.
	// Unread holds the outputs that could not be read, by name.
	Inputs  []InputBinding
	Outputs []CalcOutputValue
	Unread  map[string]error

	// Verdicts are the case's checks over this run: on its own until concludeMonteCarlo
	// settles them over the sample, which keeps the checks that are the sample's alone.
	Verdicts []AnalysisVerdict
	// contains filtered or unexported fields
}

MonteCarloRun is one run of a Simulation::MonteCarlo case: its steps performed and `observed` read, its statistics unbound until concludeMonteCarlo binds the sample's.

func (*MonteCarloRun) Conclude added in v0.9.2

func (r *MonteCarloRun) Conclude(stats MonteCarloStatistics, sample []bool) (AnalysisResult, error)

Conclude binds outOfSpec over the settled run, then reports the case's outputs and the verdicts of the sample's checks, judged over the results and all four statistics.

func (*MonteCarloRun) Context

func (r *MonteCarloRun) Context() *Context

Context is the context the run was made in, which its values are read through.

type MonteCarloStatistics

type MonteCarloStatistics struct {
	// Runs is the number of runs observed.
	Runs int64
	// Mean is the arithmetic mean of the observations.
	Mean float64
	// Deviation is their sample standard deviation, which under two runs there is none of.
	Deviation float64
	// OutOfSpec is the number of runs a check of the runs did not hold in, counted by
	// concludeMonteCarlo once the runs' checks are settled; MonteCarloSample leaves it 0.
	OutOfSpec int64
	// Unit is the unit quantity observations were taken in, which Mean and Deviation
	// are expressed in; nil when the observations were bare numbers.
	Unit *Unit
}

MonteCarloStatistics are the statistics of a sample of runs, as Simulation::MonteCarlo declares them.

func MonteCarloSample

func MonteCarloSample(runs []*MonteCarloRun) (MonteCarloStatistics, error)

MonteCarloSample is the statistics of runs, each of which observed a number or a quantity, the quantities expressed in the first run's unit; one observing none, no number, or a quantity of another dimension refuses the sample, named by its Number.

type NamedInput added in v0.9.2

type NamedInput struct {
	Name  string
	Value Value
}

NamedInput is one named argument of an action invocation: the parameter name as written and its value, given in the order the invocation wrote them.

type NoValueError

type NoValueError struct {
	Feature string
	// Ref is the written name whose read found no value, so a caller can tell a
	// read of its own expression from one made while evaluating a default.
	Ref *ast.QualifiedName
	// Symbol is the feature declaration the read reached, when it is known.
	Symbol *symbols.Symbol
}

NoValueError reports a feature a condition names that carries no value, naming the feature so a caller can tell which one is uninitialized.

func (*NoValueError) Error

func (e *NoValueError) Error() string

func (*NoValueError) Unwrap

func (e *NoValueError) Unwrap() error

type NodeBreakpoint

type NodeBreakpoint struct {
	Within []ast.Node
	Node   ast.Node
}

NodeBreakpoint is a breakpoint set by identity: on Node, in the flow of the nested action nodes Within (outermost first, as Token.Within lists them; none for the action's own).

type ObjectBehavior

type ObjectBehavior struct {
	// Name is the name the behavior answers to on the object.
	Name string
	Kind lower.ClassifierBehaviorKind
	// Symbol is the state machine or action holding the body being run, which is
	// the binding declaration itself when it states one.
	Symbol *symbols.Symbol
	// Object is the object performing the behavior.
	Object *Instance

	// State is the machine the object exhibits, nil for a performed action.
	State *StateExecutor
	// Action is the action the object performs, nil for an exhibited machine.
	Action *ActionExecutor
	// Err is the error a performed action bound by the object's type failed with,
	// recorded rather than failing the object's creation.
	Err error
	// contains filtered or unexported fields
}

ObjectBehavior is a behavior one object runs because its type exhibits or performs it: an execution of its own, bound to that object's identity.

func (*ObjectBehavior) Describe

func (b *ObjectBehavior) Describe() string

Describe names the behavior and the object running it, for diagnostics.

func (*ObjectBehavior) Member

func (b *ObjectBehavior) Member() *symbols.Symbol

Member is the declaration binding the behavior to the object's type: the exhibiting or performing usage, which is what addresses this behavior when several run the same body.

type ObjectFeature

type ObjectFeature struct {
	Name    string
	Feature *EffectiveFeature
}

ObjectFeature is a feature of an object under one of its names: the declaration its feature value reads, or its type's when it holds no value under the name.

type ObjectNamed

type ObjectNamed struct {
	ID   int64
	Path string
}

ObjectNamed is an object the moves of a witness name by the number its run gave it, bound to its materialization path, `object #2 = Plant::spare#1`, so the run replaying the witness finds the object among its own.

func (ObjectNamed) Number

func (o ObjectNamed) Number() string

Number is how the moves name the object: `object #<id>`.

func (ObjectNamed) String

func (o ObjectNamed) String() string

String spells the binding as a witness lists it and parseObject reads it back.

type ObjectVerdict

type ObjectVerdict struct {
	Kind AssertionKind
	// Element is the asserting element: the constraint, requirement or satisfy usage.
	Element *symbols.Symbol
	// Requirement is the requirement a requirement or satisfaction verdict is
	// about, whose verification cases a caller may report beside it.
	Requirement *symbols.Symbol
	// Text is the assertion as written, so an anonymous one can be named.
	Text string
	// Subject is the object evaluated against and Path the features walked to it
	// from the root, a collection element indexed as wheels[2]; empty for the root.
	Subject *Instance
	Path    []string
	Status  ValidationStatus
	// Err is the violation, or what left the assertion undecided; nil when it holds.
	Err error
}

ObjectVerdict is one assertion checked on one object of a validated tree.

type Objective

type Objective struct {
	// Name is the objective's name, empty for an anonymous one.
	Name string

	// Symbol is the objective usage's symbol.
	Symbol *symbols.Symbol

	// Type is the objective definition it is typed by, nil when untyped.
	Type *symbols.Symbol

	// Direction is the way its value is to be improved.
	Direction ObjectiveDirection

	// Value is the expression stating the value to improve, nil when the
	// objective states none.
	Value ast.Node

	// Scope is where Value's names resolve.
	Scope *symbols.Scope

	// Eval is the calc redefining the library's `eval` that states Value, nil
	// when the value is stated another way or not at all.
	Eval *symbols.Symbol

	// StepwiseEval reports an `eval` whose body computes in steps rather than
	// stating one expression, so no Value is read from it.
	StepwiseEval bool

	// Evaluates is the calc `eval` is bound to hold (`in calc :>> eval =
	// evaluationFunction;`), applied to each alternative the case's subject
	// lists; nil when `eval` states an expression or nothing.
	Evaluates *symbols.Symbol

	// Best is the objective's `best` feature, derived by the library from Eval;
	// nil when the objective is no trade-study objective.
	Best *symbols.Symbol

	// ReboundBest is a feature giving the library's bound `best` a value of its
	// own (`attribute :>> best = expression;`), which validation rejects; or nil.
	ReboundBest *symbols.Symbol

	// Conditions are the conditions the objective states itself, its own body's
	// and the ones it inherits from the model's own objective definitions: what
	// values are feasible, which a solver translates.
	Conditions []Condition

	// LibraryConditions are the conditions the objective inherits from the
	// trade-study library (`eval(selectedAlternative) == best`): about the
	// choice among the listed alternatives, which the analysis run checks and
	// no solver translates.
	LibraryConditions []Condition
}

Objective is one objective an analysis case states: which way its value is to be improved, the expression stating that value, and the conditions it states itself.

func (Objective) Text

func (o Objective) Text() string

Text renders the expression stating the objective's value as written, empty when it states none.

type ObjectiveDirection

type ObjectiveDirection int

ObjectiveDirection is the way an objective's value is to be improved, taken from the trade-study objective definition it is typed by.

const (

	// Minimize is an objective specializing TradeStudies::MinimizeObjective.
	Minimize ObjectiveDirection
	// Maximize is an objective specializing TradeStudies::MaximizeObjective.
	Maximize
)

func (ObjectiveDirection) String

func (d ObjectiveDirection) String() string

String names the direction as the model states it.

type ObservationReason added in v0.10.0

type ObservationReason string

ObservationReason says how far short of quiescence an outcome was observed: its claim holds at that point, and its strength stands.

type OccurrenceLife

type OccurrenceLife struct {
	Began int64
	Ended int64
	// Destroyed marks an end by `destroy`, after which the features hold nothing;
	// a performance that completed keeps its final values.
	Destroyed bool
}

OccurrenceLife is the lifetime of an occurrence as the describe API reports it: where in the execution order it began and ended, 0 for "not yet".

func (OccurrenceLife) String

func (l OccurrenceLife) String() string

String renders the lifetime for a debugging surface.

type OccurrenceRun added in v0.11.0

type OccurrenceRun struct {
	Occurrence *Instance
	Transfers  []PerformedTransfer
}

OccurrenceRun is what performing an occurrence definition as an interaction did: the object the occurrence materialized to, whose parts are the lifelines, and the transfers its messages were realized as, in the order performed.

type OperandTypeError

type OperandTypeError struct {
	Op      string      // the operator, as written
	Left    string      // description of the left operand's type
	Right   string      // description of the right operand's type
	Library string      // the library function that would have to declare it, if any
	Span    source.Span // span of the operator expression
}

OperandTypeError reports an operator applied to operand types it is not defined for, naming the operator and both operands and carrying the span of the expression so a surface holding the source can point at it.

func (*OperandTypeError) Error

func (e *OperandTypeError) Error() string

func (*OperandTypeError) Unwrap

func (e *OperandTypeError) Unwrap() error

type OperationArguments

type OperationArguments struct {
	Positional []Value
	Named      map[string]Value
}

OperationArguments is an invocation's argument list (KerML 8.2.5.8.3): either positional, bound to the operation's `in` and `inout` parameters in declaration order, or named. A list giving both is refused.

type OptimizationStage added in v0.11.0

type OptimizationStage struct {
	Case       *symbols.Symbol
	Objectives []Objective
	Conditions []Condition
}

OptimizationStage is one stage of a lexicographic optimization: a case, the objectives it states and the conditions bounding it — the enclosing case first, then each analysis nested in it, in declaration order.

type Outcome

type Outcome struct {
	Outputs     map[string]Value
	FinalState  string
	StateVisits []string
	// Terminated is set when the performance was ended short of its own flow: a
	// machine's transition to a terminate action, or a terminate of an occurrence
	// it belongs to. An action's own `terminate` node completes it instead.
	Terminated bool
	Err        error
	// Scope says how far short of quiescence the run was observed; no part of
	// the outcome's identity.
	Scope []ObservationReason
	// contains filtered or unexported fields
}

Outcome is what one run came to, in the observables a conformance case compares; a run that failed is an outcome of its own, Err.

func (Outcome) Context

func (o Outcome) Context() *Context

Context is the context of the run that came to this outcome, nil for an outcome built without one.

func (Outcome) RenderedOutputs

func (o Outcome) RenderedOutputs() []OutcomeOutput

RenderedOutputs spells the outputs in name order; an object two outputs hold is spelled once, the second mention being its number in the outcome. A graph is opened to the bounds the wire serializes one to.

func (Outcome) String

func (o Outcome) String() string

String renders the outcome canonically: two runs agreeing on their observables render alike, so the rendering is the outcome's identity. An object is spelled by its type and what its features hold, never by the id its run gave it.

type OutcomeOutput

type OutcomeOutput struct {
	Name string
	Text string
}

OutcomeOutput is one output of an outcome as it renders: its name and its value spelled canonically, an object by its type and what it holds.

type Parameter added in v0.11.0

type Parameter struct {
	Name      string
	IsSubject bool
	// contains filtered or unexported fields
}

Parameter is one input parameter of a calc or case as a tool binding its arguments reads it: its name, whether it is a case's subject, and the declaration a bound value answers to.

func (Parameter) Admit added in v0.11.0

func (p Parameter) Admit(ctx *Context, value *Value, what func() string) error

Admit checks the value as an argument bound to the parameter is, naming it by what.

func (Parameter) Owner added in v0.11.0

func (p Parameter) Owner() *symbols.Symbol

Owner is the behavior declaring the parameter, in whose scope its values are classified.

func (Parameter) Type added in v0.11.0

func (p Parameter) Type() *symbols.Symbol

Type is the type the parameter declares, nil where it declares none.

type PerformedTransfer added in v0.11.0

type PerformedTransfer struct {
	Name      string
	From, To  *Instance
	FromEvent string
	ToEvent   string
	Message   Message
	Performed *ActionExecutor
}

PerformedTransfer is one message realized: posted from the lifeline object holding the event it leaves to the one holding the event it reaches, and the action the receiving event performed on it, nil for none.

type ProbabilityRange added in v0.10.0

type ProbabilityRange struct{ Min, Max float64 }

ProbabilityRange is the probability the model's draws give an outcome, least to greatest over schedulers that resolve its scheduling choices.

func (ProbabilityRange) Exact added in v0.10.0

func (r ProbabilityRange) Exact() bool

Exact reports whether the range is a single probability, within floating-point tolerance.

type Quantity

type Quantity = semantics.Quantity

Quantity is a scalar quantity value, the representation the semantic layer shares with the query engine: a magnitude in a measurement reference.

type QuantityValueMapping

type QuantityValueMapping struct {
	Mapped    Quantity // the point on the scale, in the scale's unit
	Reference Quantity // the same point on the reference
}

QuantityValueMapping is one point given on the scale and on the reference it is defined against, as `quantityValueMapping` states it.

type QueuedEvent

type QueuedEvent struct {
	Signal string
	Call   string
	Args   map[string]Value
	Value  *Value
}

QueuedEvent is one occurrence a driven state performance queues before it runs: a signal by type, carrying arguments or one bare payload, or an operation call carrying arguments.

type ReplayDisagreement

type ReplayDisagreement struct {
	Reason  string
	Witness string
	Trace   string
}

ReplayDisagreement reports a replay that left another trace than its witness: how, and the two traces.

func (*ReplayDisagreement) Error

func (e *ReplayDisagreement) Error() string

func (*ReplayDisagreement) Is

func (e *ReplayDisagreement) Is(target error) bool

Is makes every ReplayDisagreement match ErrReplayDisagrees.

type ReplayError

type ReplayError struct {
	// Move is the 1-based position of the move in the witness.
	Move   int
	Choice ChoiceTaken
	Faced  string
}

ReplayError reports a witness move the run could not follow: which move, the move itself, and what the run faced instead.

func (*ReplayError) Error

func (e *ReplayError) Error() string

func (*ReplayError) Is

func (e *ReplayError) Is(target error) bool

Is makes every ReplayError match ErrReplayRefused.

type Replayed

type Replayed struct {
	Ctx *Context
	Inv *Invocation
	// Err is the error the last move raised, nil when the state is one the run went on from.
	Err error
	// contains filtered or unexported fields
}

Replayed is a witness re-run to the state it claims.

func Replay

func Replay(
	stop context.Context, fresh func() (*Context, error), start Starter, w Witness, props []CheckProperty,
) (*Replayed, error)

Replay re-runs the witness: it starts the invocation start begins in the context fresh makes, under the `replay` policy over the witness (its inputs pinned, its choices followed), and moves it as the check did until its trace equals the witness's — or, for a witness ending in a failure, until a move raises it. A witness naming a property has that property, found among props, evaluated at the state reached: it must be false or fail as the witness says. The run failing to follow a choice, ending, failing otherwise or leaving another trace is a ReplayDisagreement; a caller that goes away mid-run takes the replay with it, its error being stop's.

func ReplayExecution

func ReplayExecution(
	stop context.Context, fresh func() (*Context, error), start Starter, w Witness,
	visit func(r *Replayed, moves int) error,
) (*Replayed, error)

ReplayExecution re-runs the whole schedule as ReplaySchedule does at ScheduleEnd, calling visit at every stable state on the way, settled as a check settles, with the moves made so far. An error visit returns ends the replay with it.

func ReplaySchedule

func ReplaySchedule(
	stop context.Context, fresh func() (*Context, error), start Starter, w Witness, at int,
) (*Replayed, error)

ReplaySchedule re-runs the schedule the witness fixes, start beginning the invocation in the context fresh makes under the `replay` policy with the witness's inputs fixed first, to the stable state after move at (1-based) or, at ScheduleEnd, until the run ends with every choice followed. A run that cannot follow a choice or fix an input, ends or fails before the move, or ends with choices left is a ReplayDisagreement; a failure at the move named, or ending the run, is the Replayed's Err, for the caller to judge against the claim.

func (*Replayed) Evaluate

func (r *Replayed) Evaluate(p CheckProperty) (bool, error)

Evaluate asks the property of the replayed run's state under a readiness probe, as the check did.

func (*Replayed) FinalValue

func (r *Replayed) FinalValue(feature string) (string, error)

FinalValue spells the feature's value as the run left it, UnsetText for one holding none: `this.<name>` the performing object's, `<object>.<name>` one of several performing objects', a bare name the one behavior's own, `<behavior>.<name>` one of several's, `node.path` one under a node an action performed, `finalState` a machine's final configuration. A name nothing answers to is an unknownCheckFeatureError.

type RequirementVerifier added in v0.10.0

type RequirementVerifier interface {
	VerificationVerdictsIn(scopes []*symbols.Scope, req *symbols.Symbol) []VerificationVerdict
}

RequirementVerifier runs the verification cases in scopes verifying a requirement: a Context, or a DeclaredReader's behavior-free one.

type RunNote

type RunNote interface {
	// Describe renders the note for a diagnostic; String is its trace line.
	Describe() string
	String() string
	// Diagnostic is the note as an informational finding about the run.
	Diagnostic() diag.Diagnostic
	// Location is the file and span of the declaration the note is about; file is
	// "" when the runtime could not name one.
	Location() (file string, span source.Span)
}

RunNote is a finding a run records about itself without changing it: a choice point it made, or a guard it read only to report one and could not evaluate.

type SatisfactionSubject added in v0.11.0

type SatisfactionSubject struct {
	Object *Instance
	Root   *Instance
	Path   []string
}

SatisfactionSubject is one object a type's assertion is about, and where it was reached from: the root object holding it and the features walked down to it, the root itself with no path for an object standing on its own.

type SatisfyAssertion

type SatisfyAssertion struct {
	// Symbol is the satisfy usage itself, which is anonymous in the usual
	// `assert satisfy r by p;` form.
	Symbol *symbols.Symbol

	// Owner is the element stating the assertion (the enclosing part or
	// package), or nil at the root of a document.
	Owner *symbols.Symbol

	// Requirement is the requirement the assertion satisfies: the target of the
	// usage's reference subsetting. It is nil when the reference names nothing
	// resolvable, and when the assertion declares the requirement itself
	// (`satisfy requirement r by p { ... }`), which states its conditions.
	Requirement *symbols.Symbol

	// RequirementRef is the requirement reference as written, so an unresolved
	// one can be reported by name.
	RequirementRef string

	// Subject is the feature named by `by`, whose values the requirement is
	// evaluated against. It is nil when the assertion names no subject, and
	// when the name resolves to nothing. For a feature chain (`config.child`)
	// it is the chain's last feature.
	Subject *symbols.Symbol

	// SubjectRef is the `by` operand as written, a chain with its dots.
	SubjectRef string

	// SubjectChain is the `by` operand when it is a feature chain, whose object
	// is reached through the objects of the features before its last; nil for a
	// plain name.
	SubjectChain *ast.FeatureChainExpr

	// SubjectRoot is the feature a chained `by` operand starts from (`config`),
	// and SubjectPath the features walked from its object to the subject's
	// (`child`). Both are empty for a plain name.
	SubjectRoot *symbols.Symbol
	SubjectPath []string

	// Negated is `assert not satisfy ...`: the assertion holds when the
	// requirement is not satisfied.
	Negated bool
}

SatisfyAssertion is one satisfaction assertion an element states: `assert satisfy <requirement> by <subject>` (SysML v2 §8.3.17.15). The assertion is a requirement usage of its own — it reference-subsets the requirement it satisfies and binds that requirement's subject parameter to the feature named by `by` — so it carries a verdict the requirement alone does not: one about the values that feature actually holds.

func (*SatisfyAssertion) AssertedRequirement

func (a *SatisfyAssertion) AssertedRequirement() *symbols.Symbol

AssertedRequirement is the requirement the assertion is about: the one it references, or its own usage where the assertion declares the requirement (`satisfy requirement r by p { ... }`). It is nil for a reference naming nothing resolvable.

func (*SatisfyAssertion) StatingType added in v0.11.0

func (a *SatisfyAssertion) StatingType() *symbols.Symbol

StatingType is the type whose objects an assertion naming no `by` subject is about: the definition or usage stating it, each object of which satisfies the requirement (SysML v2 §7.20.1, a satisfy with no satisfying feature binds the subject to the owner). It is nil for an assertion naming its subject and for one stated by a package, which is about no object.

func (*SatisfyAssertion) Text

func (a *SatisfyAssertion) Text() string

Text writes the assertion as the notation does, each name quoted when it needs quoting, so an anonymous one can be named in a verdict. A `satisfy requirement r by p` form declares the requirement rather than referencing one, so it is named by the usage itself.

type SchedulePolicy

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

SchedulePolicy names how the executors resolve the choice points of a run. The zero value is the default policy, `reverse`.

func ExplorePolicy

func ExplorePolicy(budget ExploreBudget) (SchedulePolicy, error)

ExplorePolicy is the `explore` policy under the given budget: at least one run, and a depth of at least zero.

func ParseSchedulePolicy

func ParseSchedulePolicy(spelling string) (SchedulePolicy, error)

ParseSchedulePolicy reads `declared`, `reverse`, `seed:<n>`, `explore[:runs=<n>,depth=<d>]` (either option, either order) or `replay:<file>`, whose file is read here (see ParseChoices); "" is the default.

func ReplayOf

func ReplayOf(w Witness) SchedulePolicy

ReplayOf is the `replay` policy over a witness held in memory: its inputs are fixed before the first move of the run, its choices followed move for move.

func ReplayPolicy

func ReplayPolicy(choices []ChoiceTaken) SchedulePolicy

ReplayPolicy is the `replay` policy over choices held in memory, fixing no input. Its spelling names no file, so it does not read back; write the witness out to name it.

func (SchedulePolicy) Exploration

func (p SchedulePolicy) Exploration() (ExploreBudget, bool)

Exploration returns the budget of an `explore` policy, and whether the policy is one: such a policy is driven by Explore rather than set on a context.

func (SchedulePolicy) IsDefault

func (p SchedulePolicy) IsDefault() bool

IsDefault reports whether the policy is the one runs use unless told otherwise.

func (SchedulePolicy) Replay

func (p SchedulePolicy) Replay() ([]ChoiceTaken, bool)

Replay returns the choices of a `replay` policy's witness, and whether the policy is one.

func (SchedulePolicy) String

func (p SchedulePolicy) String() string

String returns the spelling ParseSchedulePolicy reads the policy back from; a replay of a witness held in memory names no file and spells `replay`.

func (SchedulePolicy) Witness

func (p SchedulePolicy) Witness() (Witness, bool)

Witness returns the witness a `replay` policy follows, and whether the policy is one.

type SchedulePolicyError

type SchedulePolicyError struct {
	Spelling string
	Reason   string
}

SchedulePolicyError reports a policy spelling that names no policy, with why.

func (*SchedulePolicyError) Error

func (e *SchedulePolicyError) Error() string

func (*SchedulePolicyError) Is

func (e *SchedulePolicyError) Is(target error) bool

Is makes every SchedulePolicyError match ErrInvalidSchedulePolicy.

type Sequence

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

Sequence is an ordered collection (slice-backed). One read empty from a quantity-typed declaration remembers the unit its elements would measure in. One a lower bound filled may end in required members not yet made (required.go).

func NewSequence

func NewSequence() *Sequence

NewSequence creates an empty Sequence.

func (*Sequence) Append

func (s *Sequence) Append(val Value)

Append adds a value to the end of the sequence.

func (*Sequence) At

func (s *Sequence) At(index int) (Value, error)

At returns the element at the given index (0-based).

func (*Sequence) Elements

func (s *Sequence) Elements() []Value

Elements returns the elements in order (for iteration); the members of a required tail are named by their reserved identities, made or not.

func (*Sequence) Size

func (s *Sequence) Size() int

Size returns the number of elements.

type Set

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

Set is a unique collection backed by hash buckets and exact comparisons. A set has no inherent order, but enumerating one has to answer in some order, and the one it answers in is the canonical order (see canonicalLess): equal sets enumerate alike, whatever order their elements were added in.

func NewSet

func NewSet() *Set

NewSet creates an empty Set whose membership needs no context.

func NewSetIn

func NewSetIn(ctx *Context) *Set

NewSetIn creates an empty Set judging membership in ctx: a point on a scale is the member its magnitude on the reference is. A nil ctx judges with no context.

func (*Set) Add

func (s *Set) Add(val Value)

Add inserts a value into the set (deduplicates by exact value equality).

func (*Set) Contains

func (s *Set) Contains(val Value) bool

Contains checks if the value is in the set.

func (*Set) Elements

func (s *Set) Elements() []Value

Elements returns all elements in canonical order.

func (*Set) Equal

func (s *Set) Equal(other *Set) bool

Equal holds when the sets have the same members, in whatever order.

func (*Set) Size

func (s *Set) Size() int

Size returns the number of unique elements.

type SetupError added in v0.10.0

type SetupError struct{ Err error }

SetupError is a run's failure to begin: no executor could be made or initialized.

func (*SetupError) Error added in v0.10.0

func (e *SetupError) Error() string

func (*SetupError) Unwrap added in v0.10.0

func (e *SetupError) Unwrap() error

type Shapes

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

Shapes records the resolved shape of every type a set of objects was materialized against, taken while that resolution is still the current one. It is what a later context compares its own resolution against to decide whether those objects still mean the same thing.

type Snapshot

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

Snapshot is the run-derived state of a Context at one point between steps: a mark in its journal, which Restore brings the run back to as often as asked until Release. The Model the context runs over is not part of it, nor are the breakpoints set on its executors: those are the debugger's, not the run's, and stay as set across a restore (a HeldImage, a copy, carries them). Every object the run had made keeps its identity across a restore; what it made after the mark is abandoned, and the identities it took are handed out again.

func (*Snapshot) Release

func (s *Snapshot) Release()

Release ends the snapshot: it is no longer restorable, and the journal keeps nothing for it. Releasing twice does nothing.

func (*Snapshot) Restore

func (s *Snapshot) Restore()

Restore brings the run back to the snapshot: what was written since is undone, what was made since is abandoned, and every executor captured stands where it stood. Snapshots taken since are released. The snapshot stays live to be restored again. It panics on a released snapshot.

type Spread

type Spread struct {
	Weight, Value float64
	About         bool
}

Spread is one term of a pooled sum of squares: Weight times the square of Value, or of Value's distance from the pool's mean when About it.

type Starter

type Starter func(*Context) (*Invocation, error)

Starter builds and starts the behaviors a check runs, in the context given; a replay starts the same invocation the same way.

type StateExecutor

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

StateExecutor executes state machines using event-driven semantics.

func (*StateExecutor) AcceptsMessage

func (e *StateExecutor) AcceptsMessage(m Message) (accepted bool, err error)

AcceptsMessage reports whether the machine would take a message in flight: it reaches this machine and triggers a transition out of an active state, or lets a do behavior parked at an accept go on. Whether a transition fires is decided by its guard; see Decide. Resolving the port a trigger accepts `via` may fail; a port it materializes on the way is discarded, as everything the preview builds.

func (*StateExecutor) ActiveLeaves

func (e *StateExecutor) ActiveLeaves() []*ast.StateNode

ActiveLeaves returns the innermost active states, one per active region, in region order; the composite states enclosing them are active too.

func (*StateExecutor) ActiveStates

func (e *StateExecutor) ActiveStates() []*ast.StateNode

ActiveStates returns the machine's active state configuration: the single active state, or one state per orthogonal region, in declaration order.

func (*StateExecutor) Call

func (e *StateExecutor) Call(operation string, args map[string]Value) (map[string]Value, error)

Call queues the call event, runs the machine through the run-to-completion step dispatching it and releases the caller with the outputs the behaviors that step fired returned, by name (PSSM 8.5.9): the operation's out and inout parameters when the machine's owner declares it, an inout unwritten by the step as the caller passed it, every output otherwise. Events that step queued and timers it armed stay for the machine's later runs; the clock does not move.

func (*StateExecutor) ClearBreakpoints

func (e *StateExecutor) ClearBreakpoints()

ClearBreakpoints removes every breakpoint; a pause already reached stands.

func (*StateExecutor) CompletionDue

func (e *StateExecutor) CompletionDue() bool

CompletionDue reports a machine paused on its completion vertex by a breakpoint: entering it completed the machine, which the next step finishes.

func (*StateExecutor) CurrentState

func (e *StateExecutor) CurrentState() ast.Node

CurrentState returns the current active state node.

func (*StateExecutor) CurrentTime

func (e *StateExecutor) CurrentTime() float64

CurrentTime returns the current instant of the clock this machine shares with every executor of its context, in seconds.

func (*StateExecutor) Decide

func (e *StateExecutor) Decide(m Message) (decision Decision, err error)

Decide decides a message as the step dispatching it would — the payload bound, the guards evaluated against the data as it stands — without taking it. The machine, its data, its budget and the message are left as they were found: a value a guard derives on the way is derived again when dispatch reads it, and an object materialized on the way — to bind the payload, or by a guard reaching an occurrence not yet built — starts its behaviors as under dispatch, so the guard reads what they make of it, then is discarded along with them and anything they sent. So is a port materialized to tell whether the message reaches the machine at all. A payload or guard error is returned. Among several enabled transitions it names the one this machine's own run would fire, its scheduler left in place. A do behavior parked at an accept the message would let go on is named too.

func (*StateExecutor) DecideTransitions

func (e *StateExecutor) DecideTransitions(m Message) (decision Decision, transitions []*lower.Transition, err error)

DecideTransitions is Decide reporting alongside the decision the transitions its Fires describe, in the same order.

func (*StateExecutor) EnclosingStates

func (e *StateExecutor) EnclosingStates(state *ast.StateNode) []*ast.StateNode

EnclosingStates returns the states written around state, outermost first; the owners lowering synthesizes for regions are not among them.

func (*StateExecutor) Enqueue

func (e *StateExecutor) Enqueue(event QueuedEvent) error

Enqueue queues one event on the executor as a case declares it.

func (*StateExecutor) EventQueue

func (e *StateExecutor) EventQueue() *EventQueue

EventQueue returns the event queue (not copied - read-only access).

func (*StateExecutor) FiredCount

func (e *StateExecutor) FiredCount() int

FiredCount counts the transitions taken so far, released ones included: a mark to read what a later step fired from.

func (*StateExecutor) FiredSince

func (e *StateExecutor) FiredSince(mark int) []FiredTransition

FiredSince returns the kept transitions taken since mark, a FiredCount read earlier, and releases those before it: the machine keeps only from the last mark.

func (*StateExecutor) FiredTransitions

func (e *StateExecutor) FiredTransitions() []FiredTransition

FiredTransitions returns the transitions kept, in firing order: compound transitions by segment, fork and join branches, and entry transitions.

func (*StateExecutor) Graph

func (e *StateExecutor) Graph() *lower.StateGraph

Graph is the lowered state graph the executor runs, which a debugger reads to place the active configuration and the transitions it fired in a rendering.

func (*StateExecutor) HasDueEvent

func (e *StateExecutor) HasDueEvent() bool

HasDueEvent reports whether an event due at the current instant is queued, which a run holding time where it is dispatches.

func (*StateExecutor) HasPendingDoWork

func (e *StateExecutor) HasPendingDoWork() bool

HasPendingDoWork reports whether some active state's do behavior still has an action to run. Such work is due now, unlike a queued event's timestamp.

func (*StateExecutor) HasPendingSignal

func (e *StateExecutor) HasPendingSignal() bool

HasPendingSignal reports whether a signal this machine reacts to is in flight: one its configuration accepts, or a do behavior under way is parked at an accept for. Such a signal is due now, unlike a queued event's timestamp: the next step delivers and dispatches it.

func (*StateExecutor) HasPendingWork

func (e *StateExecutor) HasPendingWork() bool

HasPendingWork reports whether stepping the machine can still make progress: an event is queued, a signal this machine accepts is in flight, or a state's do behavior has actions left to run.

func (*StateExecutor) HoldsEntry

func (e *StateExecutor) HoldsEntry() bool

HoldsEntry reports whether an entry cascade is waiting for its next step.

func (*StateExecutor) KeepFired

func (e *StateExecutor) KeepFired(keep bool)

KeepFired has the machine keep its firings until FiredSince releases them, as a debugger reads them; off (the default), a dispatch keeps only its own.

func (*StateExecutor) LastDispatch

func (e *StateExecutor) LastDispatch() (Dispatch, bool)

LastDispatch returns what became of the event the last ProcessNextEvent dispatched, false when it dispatched none.

func (*StateExecutor) LastEventAt

func (e *StateExecutor) LastEventAt() float64

LastEventAt returns the instant the machine last dispatched an event at, zero before it dispatched any.

func (*StateExecutor) NextWait

func (e *StateExecutor) NextWait() (float64, bool)

NextWait returns the instant the machine's earliest wait — a timer, or a do behavior paused on the clock — comes due at, false when none is set for later than the clock's instant.

func (*StateExecutor) NoteCount

func (e *StateExecutor) NoteCount() int

NoteCount is how many notes the executor's run has made so far.

func (*StateExecutor) Notes

func (e *StateExecutor) Notes() []RunNote

Notes returns what the executor's run noted so far, in order; see Context.Notes.

func (*StateExecutor) NotesSince

func (e *StateExecutor) NotesSince(mark int) []RunNote

NotesSince returns what the executor's run noted since mark, a NoteCount read earlier.

func (*StateExecutor) Outcome

func (e *StateExecutor) Outcome() Outcome

Outcome is the outcome of the performance so far: the configuration the machine rests in, the states it entered and the values it holds.

func (*StateExecutor) OutgoingTransitions

func (e *StateExecutor) OutgoingTransitions() []*lower.Transition

OutgoingTransitions lists the transitions dispatch could select now: those out of each active leaf and then of each state enclosing it, innermost first as dispatch tries them, each in declaration order and a shared enclosing state's once.

func (*StateExecutor) PausedAt

func (e *StateExecutor) PausedAt() ast.Node

PausedAt is the breakpoint state or pseudostate the last run paused at, nil when none did.

func (*StateExecutor) Performer

func (e *StateExecutor) Performer() *Instance

Performer is the object this machine is performed by, nil for none.

func (*StateExecutor) PollChangeEvents

func (e *StateExecutor) PollChangeEvents() (dispatched bool, err error)

PollChangeEvents re-tests the change conditions the active configuration watches and takes the transitions they enable, reporting whether a rise was dispatched: the step RunToCompletion takes, for a driver that steps the machine.

func (*StateExecutor) ProcessNextEvent

func (e *StateExecutor) ProcessNextEvent() (err error)

ProcessNextEvent processes the next event from the queue (for REPL stepping). It is the same step RunToCompletion repeats: every active state's do behavior advances by one action, then the next event is dispatched. Advancing the do behaviors is progress in itself, so a step that ran one and found no event to dispatch succeeds — the completion transition it enables is queued next. With nothing due but a timer running, the shared clock advances to the earliest wait (running whatever else is due there) until this machine's next event is due.

func (*StateExecutor) RegionOf added in v0.10.0

func (e *StateExecutor) RegionOf(state *ast.StateNode) *ast.StateRegion

RegionOf returns the innermost orthogonal region a state stands in, or nil when the state is outside every region.

func (*StateExecutor) Release

func (e *StateExecutor) Release()

Release withdraws a machine its driver is done with from the clock, ending the do behaviors paused on it; safe to call more than once.

func (*StateExecutor) Resume

func (e *StateExecutor) Resume() bool

Resume returns a machine suspended at quiescence to running, so a driver that makes work available — advancing time, or delivering an event — can step it again. A completed or failed machine is left as it is; one paused on its completion vertex completes as the next step.

func (*StateExecutor) RunDoRound

func (e *StateExecutor) RunDoRound() (ran int, err error)

RunDoRound advances every active state's do behavior by one action, without dispatching any event, and reports how many actions ran.

func (*StateExecutor) RunToCompletion

func (e *StateExecutor) RunToCompletion() error

RunToCompletion processes queued events until the machine completes or has no event or running do behavior left, at which point it suspends. A state's do behavior runs while the state is active: each run-to-completion step advances every active state's do behavior by one action and then dispatches one event, so concurrently active states interleave instead of one running to the end at entry, and leaving a state abandons the rest of its do behavior.

Change conditions are re-tested per micro-step — after the do round, before the next queued event, and again at quiescence — a tool-defined cadence, since KerML has no clock (docs/project/spec-compliance.md).

The run is bounded by the context's event and do action budgets (OPENSYSML_MAX_EVENTS, OPENSYSML_MAX_DO_STEPS), so a cyclic machine reports a typed error instead of spinning forever. A poll that fires nothing costs no budget; a change transition taken counts as one step, like a dispatched event.

func (*StateExecutor) RunToQuiescence

func (e *StateExecutor) RunToQuiescence() error

RunToQuiescence runs the machine as RunToCompletion does, but leaves a timer set for later waiting on the clock rather than advancing to it: the configuration an object settles into is the one reached at the time it was materialized, and a timer it is waiting on is driven by advancing the clock.

func (*StateExecutor) SendSignal

func (e *StateExecutor) SendSignal(signalType string, args map[string]Value)

SendSignal injects a signal event into the state machine. This is the primary API for driving state machines with external signals. The signal is enqueued and will be processed on the next ProcessNextEvent call.

func (*StateExecutor) SetBreakpointAt

func (e *StateExecutor) SetBreakpointAt(vertex ast.Node)

SetBreakpointAt pauses a run once the dispatch entering the state, or passing through the pseudostate, completes, even one leaving the state again; what is still due then waits until the machine resumes. Other nodes are ignored.

func (*StateExecutor) SetTrace

func (e *StateExecutor) SetTrace(trace *TraceRecorder)

SetTrace sets the trace recorder for this executor and the context it evaluates in.

func (*StateExecutor) State

func (e *StateExecutor) State() ExecutionState

State returns current execution state.

func (*StateExecutor) StateData

func (e *StateExecutor) StateData() map[string]Value

StateData returns a copy of state machine local data, together with the attributes each state owns under that state's path (`nested.hits`), which two usages of one state definition hold separately.

func (*StateExecutor) StateDataWithError added in v0.10.0

func (e *StateExecutor) StateDataWithError() (map[string]Value, error)

StateDataWithError returns state data after deriving current tracking cells. A value whose inactive-state reference cannot be read is omitted and reported.

func (*StateExecutor) StateMachineSymbol

func (e *StateExecutor) StateMachineSymbol() *symbols.Symbol

StateMachineSymbol returns the state machine being executed.

func (*StateExecutor) StatePath

func (e *StateExecutor) StatePath(state *ast.StateNode) string

StatePath is state's name qualified by the states written around it (`on.run`).

func (*StateExecutor) StateStack

func (e *StateExecutor) StateStack() []*ast.StateNode

StateStack returns a copy of the state stack (active configuration).

func (*StateExecutor) Suspend

func (e *StateExecutor) Suspend() bool

Suspend parks a running machine back at quiescence, for a driver that resumed it, found nothing to do and must not report it as running.

func (*StateExecutor) SuspendReason

func (e *StateExecutor) SuspendReason() string

SuspendReason says why a machine that cannot progress cannot: the change conditions it waits on, or that nothing is left that could fire.

func (*StateExecutor) TakesMessage

func (e *StateExecutor) TakesMessage(m Message) (takes bool, err error)

TakesMessage previews whether delivery would let this machine take the message: it reacts to it and does not yield it to a sibling machine that would fire.

func (*StateExecutor) TriggeredBy

func (e *StateExecutor) TriggeredBy(m Message) (triggered bool, err error)

TriggeredBy previews whether a transition out of an active or enclosing state is triggered by the message, whatever its guard; do behaviors aside.

func (*StateExecutor) WatchesChangeCondition

func (e *StateExecutor) WatchesChangeCondition() bool

WatchesChangeCondition reports whether the active configuration watches a change condition, which data written outside the machine can make true.

func (*StateExecutor) WriteAttribute

func (e *StateExecutor) WriteAttribute(name string, value Value) error

WriteAttribute assigns an attribute the machine declares from outside it, between its steps, with the checks an assignment in its behavior gets.

type TakingAccept

type TakingAccept struct {
	Param  string // the parameter the accept binds, "" where it binds none
	Node   string // the accept node's own name, "" for an anonymous one
	Within string // the dotted path of the nested performance parked there, "" for the action's own flow
}

TakingAccept is the accept a message in flight would let a parked token go on from, and the performance it is parked in.

func (TakingAccept) String

func (a TakingAccept) String() string

String names the accept as a report reads it: `accept g`, `accept g of inner`.

type TensorQuantity

type TensorQuantity struct {
	Dimensions []int64
	Num        []semantics.Value
	Units      []Unit
	// IsBound is `isBound` when BoundKnown; a calculation the library gives no body
	// leaves its result's boundness unstated.
	IsBound    bool
	BoundKnown bool
	// MRef is the TensorMeasurementReference object the tensor was built over, whose
	// members `mRef` keeps answering; 0 for one known by its components only.
	MRef int64
}

TensorQuantity is a Quantities::TensorQuantityValue of order two or more: row-major `num` over `dimensions`, each in its component's unit. Orders 0 and 1 are Quantity and VectorQuantity.

type Token

type Token struct {
	ID       int64    // Unique token ID
	Location ast.Node // Current node position

	// Via is the succession the token travelled to reach Location; the zero edge for a
	// token no succession delivered (a flow's first, or the one a synchronized node performs with).
	Via lower.ActionEdge

	// Wait records that this token is parked at an accept node: the accept
	// found no message it could consume, so the action is suspended there
	// until one arrives. It is nil for every token that is free to advance.
	Wait *AcceptWait
	// contains filtered or unexported fields
}

Token represents a control token in action execution. It carries no values of its own: the action's features are one space every token shares (see ActionExecutor.Data).

func (Token) Within

func (t Token) Within() []ast.Node

Within lists the nested action nodes whose own flows the token runs in, outermost first; empty for a token in the action's own flow.

type ToolAnswer

type ToolAnswer struct {
	Outputs  map[string]Value
	Diverged bool
}

ToolAnswer is what one invocation established: the values bound to the call's outputs by parameter name, and whether an earlier invocation with equal inputs answered differently.

type ToolCall

type ToolCall struct {
	// Action is the annotated action or calc the tool computes.
	Action   *symbols.Symbol
	ToolName string
	URI      string
	Inputs   []ToolInput
	Outputs  []ToolOutput
	// contains filtered or unexported fields
}

ToolCall is one performance or calculation of an action or calc annotated ToolExecution, as the external tool sees it: the tool and URI the metadata names, the inputs read from the run keyed by their ToolVariable names, and the outputs the tool is to answer.

func (*ToolCall) Bind

func (c *ToolCall) Bind(outputs map[string]ToolValue) (map[string]Value, error)

Bind reads the tool's outputs, keyed by ToolVariable name, as the values of the call's output parameters: each quantity converted to its parameter's declared unit. An output missing, unknown, or not readable as its parameter's value is a ToolError.

func (*ToolCall) Context added in v0.9.2

func (c *ToolCall) Context() *Context

Context is the context the call's performance runs in, nil for a call built outside one.

func (*ToolCall) ConvertInput added in v0.9.2

func (c *ToolCall) ConvertInput(in ToolInput, unit string) (semantics.Value, error)

ConvertInput expresses an input's number in the unit spelled: from is the unit the value was sent in, to the unit the tool answers in. The units must share a dimension, and the call must run under a context to read unit expressions.

type ToolDivergence

type ToolDivergence struct {
	Tool   string
	Action string
	File   string
	Span   source.Span
}

ToolDivergence is a tool answering two performances or calculations with equal inputs differently: the outcome table over it is not reproducible, and the run says so without changing.

func (ToolDivergence) Describe

func (d ToolDivergence) Describe() string

Describe renders the divergence for a diagnostic.

func (ToolDivergence) Diagnostic

func (d ToolDivergence) Diagnostic() diag.Diagnostic

Diagnostic is the divergence as a finding about the run, a warning since the results resting on the tool are not reproducible.

func (ToolDivergence) Location

func (d ToolDivergence) Location() (string, source.Span)

Location is the annotated action's or calc's declaration.

func (ToolDivergence) String

func (d ToolDivergence) String() string

String is the trace line the divergence is recorded as.

type ToolError

type ToolError struct {
	Tool   string
	Kind   ToolErrorKind
	Detail string
}

ToolError reports one tool invocation's failure: the tool, what failed, and the detail.

func (*ToolError) Error

func (e *ToolError) Error() string

Error names the tool, the kind and the detail.

func (*ToolError) Is

func (e *ToolError) Is(target error) bool

Is matches ErrTool.

type ToolErrorKind

type ToolErrorKind int

ToolErrorKind is what failed in one tool invocation.

const (
	// ToolProcessFailed is a process that could not be started or exited non-zero.
	ToolProcessFailed ToolErrorKind = iota
	// ToolMalformed is a reply that is not one JSON object of the protocol, or a value in it
	// the receiving parameter cannot read.
	ToolMalformed
	// ToolMissingOutput is an `out` parameter the reply gave no value for.
	ToolMissingOutput
	// ToolUnknownOutput is a reply value no ToolVariable of the action receives.
	ToolUnknownOutput
	// ToolTimeout is a process that outlived OPENSYSML_TOOL_TIMEOUT.
	ToolTimeout
	// ToolRefused is a reply carrying the tool's own error message.
	ToolRefused
	// ToolUnsentInput is an input the protocol carries no value of.
	ToolUnsentInput
)

func (ToolErrorKind) String

func (k ToolErrorKind) String() string

String names the kind as the error spells it.

type ToolInput

type ToolInput struct {
	Variable  string
	Parameter string
	Value     ToolValue
}

ToolInput is one `in` or `inout` parameter's value, under its ToolVariable name.

type ToolNotRegisteredError

type ToolNotRegisteredError struct {
	Tool string
}

ToolNotRegisteredError reports the tool a performance named and nothing answers to.

func (*ToolNotRegisteredError) Error

func (e *ToolNotRegisteredError) Error() string

Error is the refusal, naming the environment variable that registers tools.

func (*ToolNotRegisteredError) Is

func (e *ToolNotRegisteredError) Is(target error) bool

Is matches errToolNotRegistered.

type ToolOutput

type ToolOutput struct {
	Variable  string
	Parameter string
	// Declared is the parameter's declaration, whose unit the tool's answer is converted to.
	Declared *symbols.Symbol
}

ToolOutput is one `out` or `inout` parameter the tool answers, under its ToolVariable name.

type ToolRunner

type ToolRunner interface {
	RunTool(call *ToolCall) (ToolAnswer, error)
}

ToolRunner runs the tool a ToolExecution names for one performance or calculation, binding the tool's outputs through ToolCall.Bind. A context with no runner attached refuses every tool-computed action or calc as not registered.

type ToolValue

type ToolValue struct {
	Value semantics.Value
	Text  string
	Unit  string
	Items []ToolValue
}

ToolValue is one value as the tool protocol carries it: a number or truth in Value, or a string in Text when Value is invalid, and for a quantity the unit expression it is measured in. A non-nil Items makes the value a sequence: each item is a scalar (its own Value/Text, Unit empty — the sequence's Unit is shared by every item); an empty sequence is a non-nil empty slice. Readers always allocate Items non-nil.

func ToolValueOf

func ToolValueOf(held Value) (ToolValue, bool)

ToolValueOf is a value as the tool protocol carries it; false for one it does not carry. A sequence carries its elements in Items; a unit every element shares is hoisted to the sequence's Unit.

type TraceKind

type TraceKind int

TraceKind classifies a trace record.

const (
	// TraceLine is a record the trace prints as a line and a query does not read
	// past its text: steps, evaluations, calculations, object lifecycle.
	TraceLine TraceKind = iota
	// TraceAccept is an event a behavior took off its queue: a signal or an
	// operation call. The trace prints no line for it.
	TraceAccept
	// TraceSend is a message posted onto the bus. The trace prints no line for it.
	TraceSend
	// TraceTransition is a transition fired.
	TraceTransition
	// TraceEntry is a state entered.
	TraceEntry
	// TraceExit is a state exited.
	TraceExit
	// TraceDo is one step of a state's do behavior.
	TraceDo
	// TraceChoice is a choice point the run drew.
	TraceChoice
	// TraceGuard is a guard the run read to report a choice and could not evaluate.
	TraceGuard
	// TraceTerminate is a state machine's performance ending without exiting its states:
	// a terminate action, or the end of the occurrence performing it.
	TraceTerminate
)

func (TraceKind) String

func (k TraceKind) String() string

String names the kind as a query reads it.

type TraceOrigin

type TraceOrigin struct {
	At       float64
	Object   *Instance
	Behavior *symbols.Symbol
}

TraceOrigin is where a record was made: the clock's instant, the object whose behavior made it and that behavior, each nil where the run has none.

type TraceRecord

type TraceRecord struct {
	Kind   TraceKind
	Origin TraceOrigin
	// State is the state entered, exited or stepped; From and To are a fired
	// transition's endpoints.
	State, From, To string
	// Path qualifies a state by its written enclosing states; Region qualifies
	// the innermost orthogonal region, and is empty outside every region.
	Path, Region string
	// Source is where the state an entry or exit names was declared; zero when unknown.
	Source symbols.Origin
	// Event is the trigger a transition fired on, or the signal or operation an
	// accept or send carries; Payload is the message's payload.
	Event   string
	Payload map[string]Value
	// Message is the Serial of the message a send posted or an accept took; 0 for none.
	Message uint64
	// Target is the object a send was addressed to, nil for a broadcast or a
	// destination named only as text (kept in To).
	Target *Instance
	// Action reports an entry or exit behavior ran with the entry or exit.
	Action bool
	// Note is a TraceChoice's or TraceGuard's note.
	Note RunNote
	// contains filtered or unexported fields
}

TraceRecord is one entry of a run's trace. The printed line is derived from the record, so what a query reads and what `-trace` prints cannot drift.

func (TraceRecord) Line

func (r TraceRecord) Line() (line string, printed bool)

Line is the line the trace prints for the record; printed is false for a record the trace keeps without printing.

func (TraceRecord) Machine added in v0.10.0

func (r TraceRecord) Machine() string

Machine names the behavior a record came from as its object exhibits it, or as declared when it is anonymous or the record has no object.

func (TraceRecord) PayloadTexts added in v0.10.0

func (r TraceRecord) PayloadTexts() []string

PayloadTexts renders a message payload as `name = value` entries in name order.

func (TraceRecord) Text

func (r TraceRecord) Text() string

Text is what a query reads as the record's text: its printed line, or for an accept or send its kind and event.

type TraceRecorder

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

TraceRecorder keeps a run's trace as typed records, in the order they were made, and prints them as the deterministic lines the golden trace tests read.

Evaluation entries are recorded in post-order: the sub-expressions of an expression appear before it, indented one level deeper, so sibling evaluation order and nesting are both readable off the trace. A constant sub-expression is answered by the semantic constant folder without evaluating its operands, so it appears with no children.

Clear marks records printed rather than dropping them: a query reads the whole run, or the most recent limit records of one bounded by NewEventRecorder.

func NewEventRecorder

func NewEventRecorder(limit int) *TraceRecorder

NewEventRecorder creates a recorder nothing prints, keeping the most recent limit records (all when 0).

func NewTraceRecorder

func NewTraceRecorder() *TraceRecorder

NewTraceRecorder creates a new trace recorder.

func (*TraceRecorder) Clear

func (tr *TraceRecorder) Clear()

Clear marks every record printed, so Entries starts over, and resets nesting depth.

func (*TraceRecorder) Dropped

func (tr *TraceRecorder) Dropped() (count int, upTo float64)

Dropped reports how many records the limit discarded and the instant of the last of them.

func (*TraceRecorder) Entries

func (tr *TraceRecorder) Entries() []string

Entries returns the lines of the records made since the last Clear, in order.

func (*TraceRecorder) RecordAccept

func (tr *TraceRecorder) RecordAccept(origin TraceOrigin, serial uint64, event string, payload map[string]Value)

RecordAccept records an event a behavior took off its queue: the signal or operation it names, with the payload it carries.

func (*TraceRecorder) RecordNote

func (tr *TraceRecorder) RecordNote(origin TraceOrigin, n RunNote)

RecordNote records a run's note where it was made: before the step line of the action step it belongs to, or before the transition it decided.

func (*TraceRecorder) RecordSend

func (tr *TraceRecorder) RecordSend(origin TraceOrigin, msg Message, target *Instance)

RecordSend records a message posted onto the bus by the object at origin, or from outside the run where it has none.

func (*TraceRecorder) RecordStateEntry

func (tr *TraceRecorder) RecordStateEntry(origin TraceOrigin, state, path, region string, hasEntryAction bool)

RecordStateEntry records entering a state with optional entry action execution.

func (*TraceRecorder) RecordStateExit

func (tr *TraceRecorder) RecordStateExit(origin TraceOrigin, state, path, region string, hasExitAction bool)

RecordStateExit records exiting a state with optional exit action execution.

func (*TraceRecorder) RecordStateTransition

func (tr *TraceRecorder) RecordStateTransition(origin TraceOrigin, fromState, toState string, event string)

RecordStateTransition records a transition fired, with the trigger it fired on.

func (*TraceRecorder) Records

func (tr *TraceRecorder) Records() []TraceRecord

Records returns the records kept in order, printed ones included. The slice is read-only.

func (*TraceRecorder) String

func (tr *TraceRecorder) String() string

String returns the trace as a single string (newline-separated entries).

type Traversal

type Traversal struct {
	Token  int64
	Edge   lower.ActionEdge
	Within []ast.Node
}

Traversal is one succession a token took: which token, the edge, and the nested action nodes whose own flows it was running in (see Token.Within).

type Undetermined

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

Undetermined is the payload of a ValUndetermined value: what the model does fix about a result it leaves open — the count its values conform to, the values it certainly holds.

func (*Undetermined) Count

func (u *Undetermined) Count() semantics.Range

Count is the multiplicity the undetermined values conform to.

func (*Undetermined) Feature added in v0.11.0

func (u *Undetermined) Feature() *symbols.Symbol

Feature is the feature the result is the read of, nil for a computed result.

func (*Undetermined) Reason

func (u *Undetermined) Reason() string

Reason names why the result is undetermined, phrased for a diagnostic.

func (*Undetermined) Unset added in v0.11.0

func (u *Undetermined) Unset() *symbols.Symbol

Unset is the feature nothing gives a value to that the result is open for — read directly or through the operations computing from it — nil where the count alone is open.

func (*Undetermined) Unsets added in v0.11.0

func (u *Undetermined) Unsets() []*symbols.Symbol

Unsets lists every feature with no value the result is open for, in the order the evaluation met them; empty when it is open only for a count the model leaves open.

type UnevaluableGuard

type UnevaluableGuard struct {
	// Step is the action step the guard was read in, 0 for a state machine.
	Step int
	// Where names the decision node or the state and event, as a ChoicePoint does.
	Where string
	// Alternative is the branch or transition by declaration position, as a
	// ChoicePoint lists it.
	Alternative string
	// Reason is the evaluation error.
	Reason string
	File   string
	Span   source.Span
}

UnevaluableGuard is a guard an executor read only to report a choice, once a branch or transition already held, and could not evaluate. A guard with no result is not true, so its succession is not selected; the run is unchanged.

func (UnevaluableGuard) Describe

func (g UnevaluableGuard) Describe() string

Describe renders the guard for a diagnostic: where it was read, which alternative it guards and why it has no result.

func (UnevaluableGuard) Diagnostic

func (g UnevaluableGuard) Diagnostic() diag.Diagnostic

Diagnostic is the guard as a finding about the run: informational, since the library selects no succession whose guard is not true and defines no failure.

func (UnevaluableGuard) Location

func (g UnevaluableGuard) Location() (string, source.Span)

Location is where the guard was declared.

func (UnevaluableGuard) String

func (g UnevaluableGuard) String() string

String is the trace line the guard is recorded as.

type Unit

type Unit = semantics.Unit

Unit is a measurement reference as a quantity carries it.

type UnresolvedActionError added in v0.11.0

type UnresolvedActionError struct {
	Name   string // the name as written
	Detail string // why the name resolves to nothing, when there is more to say
}

UnresolvedActionError reports a perform, include or action reference naming no behavior the runtime can find. It is a kind of ErrUnresolvedReference.

func (*UnresolvedActionError) Error added in v0.11.0

func (e *UnresolvedActionError) Error() string

func (*UnresolvedActionError) Unwrap added in v0.11.0

func (e *UnresolvedActionError) Unwrap() error

type ValidationReport

type ValidationReport struct {
	Root     *Instance
	Verdicts []ObjectVerdict
	// Bounded is true when the walk left nesting unreached — deeper than it
	// descends, or past its budget — so the unreached objects are unvalidated.
	Bounded bool
	// Unread are the feature values that could not be read, whose objects went unvalidated.
	Unread []error
}

ValidationReport is what validating an object and the objects it holds found.

func (ValidationReport) Complete

func (r ValidationReport) Complete() bool

Complete reports whether the walk reached every object the root holds.

func (ValidationReport) Count

func (r ValidationReport) Count(status ValidationStatus) int

Count is how many verdicts have status.

func (ValidationReport) Status

Status is the status the report is judged by: one violation makes the object invalid whatever else is undecided, and one undecided assertion leaves it unshown.

func (ValidationReport) Valid

func (r ValidationReport) Valid() bool

Valid reports whether the object is shown valid: it states at least one assertion, every assertion holds and every held object was reached.

type ValidationStatus

type ValidationStatus int

ValidationStatus is what checking one assertion on one object decided.

const (
	// ValidationHolds is the assertion evaluating to true on the object.
	ValidationHolds ValidationStatus = iota
	// ValidationViolated is the model answering the assertion false.
	ValidationViolated
	// ValidationUndecided is an assertion that could not be evaluated.
	ValidationUndecided
)

func (ValidationStatus) String

func (s ValidationStatus) String() string

String names the status for a report a machine reads.

type Value

type Value struct {
	Kind     ValueKind
	Const    semantics.Value // ValConst: reuse static evaluator
	Instance int64           // ValInstance: instance ID; ValVariant: materialized object, 0 for none
	// contains filtered or unexported fields
}

Value is a runtime-evaluable value. The scalar payload stays inline because arithmetic copies values through every evaluator frame; the rarer payloads share one slot so the struct stays at 64 bytes.

func ConstValue added in v0.11.0

func ConstValue(c semantics.Value) Value

ConstValue wraps a numeric constant as a runtime value.

func DeclaredMeasurementRef

func DeclaredMeasurementRef(sem *semantics.Model, sym *symbols.Symbol, text string, term semantics.UnitTerm) Value

DeclaredMeasurementRef is the reference a unit declaration names, reducing to term, spelt as text (`SI::km`) or, given none, by its symbol (`km`).

func EnumeratedValue

func EnumeratedValue(sym *symbols.Symbol, scalar Value) Value

EnumeratedValue is scalar as the value of the enumeration literal sym: what `high = 3` evaluates to, rebuilt from a wire form that carries both.

func NewArrayValue

func NewArrayValue(dimensions []int64, elements []Value) Value

NewArrayValue wraps an array over its row-major elements; arrayOf checks the invariant `flattenedSize == size(elements)`.

func NewComplex

func NewComplex(z complex128) Value

NewComplex is the value of one complex number. One with a zero imaginary part is the Real its real part is, as 4 / 2 is the Integer 2: equal to it, and classified as it is.

func NewCoordinateFrameValue

func NewCoordinateFrameValue(frame *CoordinateFrame) Value

NewCoordinateFrameValue wraps a frame as a value.

func NewCoordinateTransformationValue

func NewCoordinateTransformationValue(t *CoordinateTransformation) Value

NewCoordinateTransformationValue wraps a transformation as a value.

func NewEnumLiteral

func NewEnumLiteral(sym *symbols.Symbol) Value

NewEnumLiteral is the value an enumeration literal that declares no value of its own evaluates to: the identity of that literal.

func NewMeasurementRefValue

func NewMeasurementRefValue(unit Unit) Value

NewMeasurementRefValue wraps a unit as a measurement reference value.

func NewMetaobject

func NewMetaobject(element, metaclass *symbols.Symbol) Value

NewMetaobject is the value `x meta T` yields for the element x names: that element as an instance of metaclass, the reflective metaclass of its declaration.

func NewQuantityValue

func NewQuantityValue(q *Quantity) Value

NewQuantityValue wraps a magnitude expressed in a measurement unit.

func NewSequenceValue

func NewSequenceValue(seq *Sequence) Value

NewSequenceValue wraps an ordered collection. A nil sequence is the empty one.

func NewSetValue

func NewSetValue(set *Set) Value

NewSetValue wraps a unique collection. A nil set is the empty one.

func NewStringValue

func NewStringValue(s string) Value

NewStringValue is the value of a string.

func NewTensorQuantityValue

func NewTensorQuantityValue(dimensions []int64, num []semantics.Value, units []Unit) Value

NewTensorQuantityValue wraps a tensor quantity; num and units hold one entry per component, flattenedSize of dimensions in all.

func NewUndeterminedValue

func NewUndeterminedValue(reason string, count semantics.Range) Value

NewUndeterminedValue is an undetermined result of count values, for reason.

func NewVectorQuantityValue

func NewVectorQuantityValue(num []semantics.Value, units []Unit) Value

NewVectorQuantityValue wraps a vector quantity; num and units are the same length.

func NewVectorValue

func NewVectorValue(elements []semantics.Value) Value

NewVectorValue wraps the vector of the given numeric components.

func (Value) Array

func (v Value) Array() *Array

Array is the payload of a ValArray; nil for every other kind.

func (Value) Complex

func (v Value) Complex() complex128

Complex is the number a ValComplex is; 0 for every other kind.

func (Value) CoordinateFrame

func (v Value) CoordinateFrame() *CoordinateFrame

CoordinateFrame is the payload of a ValCoordinateFrame; nil for every other kind.

func (Value) CoordinateTransformation

func (v Value) CoordinateTransformation() *CoordinateTransformation

CoordinateTransformation is the payload of a ValCoordinateTransformation; nil for every other kind.

func (Value) EnumerationLiteral

func (v Value) EnumerationLiteral() *symbols.Symbol

EnumerationLiteral is the literal a value is: a ValEnumLiteral itself, or the literal a scalar was evaluated from. Nil for a value that is no literal.

func (Value) Function

func (v Value) Function() *symbols.Symbol

Function is the calc a ValFunction is a value of — the definition or usage it was read from; nil for every other kind.

func (Value) FunctionClosesOverBody

func (v Value) FunctionClosesOverBody() bool

FunctionClosesOverBody reports a ValFunction closing over the bindings of the behavior body its calc is declared in, which nothing outside that run can rebuild.

func (Value) FunctionName

func (v Value) FunctionName() string

FunctionName is the qualified name of the calc a ValFunction is a value of, as the wire and diagnostics spell it.

func (Value) FunctionSelf

func (v Value) FunctionSelf() *Instance

FunctionSelf is the object a ValFunction's feature names resolve against, nil for a function closing over none.

func (Value) Literal

func (v Value) Literal() *symbols.Symbol

Literal is the enumeration literal a ValEnumLiteral is: a literal is its own identity, so two values are the same literal exactly when they name the same declaration. Nil for every other kind.

func (Value) LiteralText

func (v Value) LiteralText() string

LiteralText renders an enumeration literal as it is written, qualified by the enumeration it is a literal of: `Color::red`.

func (Value) MeasurementRef

func (v Value) MeasurementRef() *MeasurementRef

MeasurementRef is the payload of a ValMeasurementRef; nil for every other kind.

func (Value) MetaobjectClass

func (v Value) MetaobjectClass() *symbols.Symbol

MetaobjectClass is the reflective metaclass a ValMetaobject is an instance of; nil for every other kind.

func (Value) MetaobjectElement

func (v Value) MetaobjectElement() *symbols.Symbol

MetaobjectElement is the element a ValMetaobject denotes; nil for every other kind.

func (Value) Object

func (v Value) Object() (int64, bool)

Object returns the object a value denotes: an instance, or the object a selected variant materialized.

func (Value) Quantity

func (v Value) Quantity() *Quantity

Quantity is the payload of a ValQuantity; nil for every other kind.

func (Value) Scalar

func (v Value) Scalar() Value

Scalar is v shorn of any enumeration literal identity: the bare scalar a scalar-valued literal equals, or v itself for any other value.

func (Value) Sequence

func (v Value) Sequence() *Sequence

Sequence is the collection of a ValSequence; nil for every other kind.

func (Value) Set

func (v Value) Set() *Set

Set is the collection of a ValSet; nil for every other kind.

func (Value) Sole added in v0.11.0

func (v Value) Sole() Value

Sole is the one value a one-element sequence or set holds, or v itself for any other value: what a consumer taking one value reads from a held result.

func (Value) Str

func (v Value) Str() string

func (Value) TensorQuantity

func (v Value) TensorQuantity() *TensorQuantity

TensorQuantity is the payload of a ValTensorQuantity; nil for every other kind.

func (Value) Undetermined

func (v Value) Undetermined() *Undetermined

Undetermined returns the payload of a ValUndetermined value, nil for any other.

func (Value) Variant

func (v Value) Variant() *symbols.Symbol

Variant is the variant a ValVariant was bound to; nil for every other kind.

func (Value) Vector

func (v Value) Vector() *Vector

Vector is the payload of a ValVector; nil for every other kind.

func (Value) VectorQuantity

func (v Value) VectorQuantity() *VectorQuantity

VectorQuantity is the payload of a ValVectorQuantity; nil for every other kind.

type ValueKind

type ValueKind int

ValueKind distinguishes runtime value types.

const (
	ValInvalid ValueKind = iota
	ValConst             // wraps semantics.Value (int/real/bool/infinity)
	ValNull
	ValString
	ValInstance
	ValSequence
	ValSet

	ValQuantity                 // a magnitude and the measurement unit it is expressed in
	ValVariant                  // the variant selected for a variation, and the object it materializes
	ValEnumLiteral              // one literal of an enumeration definition, identified by itself
	ValComplex                  // one complex number, its real and imaginary parts together
	ValArray                    // a Collections::Array: its dimensions and its row-major elements
	ValVector                   // a NumericalVectorValue: the numbers of its one dimension
	ValVectorQuantity           // a VectorQuantityValue: a vector with a measurement unit per axis
	ValMeasurementRef           // a ScalarMeasurementReference: a unit by declaration and reduction
	ValTensorQuantity           // a TensorQuantityValue: an array of numbers with a measurement unit per component
	ValCoordinateFrame          // a VectorMeasurementReference: a frame's axes, or a measurement scale's one
	ValCoordinateTransformation // a CoordinateTransformation: a placement of one frame in another
	ValFunction                 // a calc as a value: its lowered shape closed over the environment it was read in
	ValMetaobject               // an element of the model as an instance of its reflective metaclass (`x meta T`)
	ValUndetermined             // a model-level result the model does not determine; see Undetermined

)

func (ValueKind) String

func (k ValueKind) String() string

String names the kind, so diagnostics quoting it read as more than an index.

type Vector

type Vector struct {
	Elements []semantics.Value
	// Object is the NumericalVectorValue object the value was read from, which keeps
	// answering the members a specialization adds; 0 for a vector made by value.
	Object int64
}

Vector is a VectorValues::NumericalVectorValue: the numbers of an Array of one dimension, its `dimension`.

func (*Vector) Dimension

func (v *Vector) Dimension() int

Dimension is the number of components.

type VectorQuantity

type VectorQuantity struct {
	Num   []semantics.Value
	Units []Unit
	// Frame is the coordinate frame the vector was written over (`(1, 2, 3) [datum]`),
	// whose axes Units are; nil for one written over a scalar unit.
	Frame *CoordinateFrame
}

VectorQuantity is a Quantities::VectorQuantityValue: the numbers `num` and the unit each axis of its measurement reference (`mRef.mRefs`) is expressed in.

type VerdictKind

type VerdictKind string

VerdictKind is the verdict a run of a verification case's body produced, one literal of the library's VerdictKind enumeration.

const (
	// VerdictPass is a body whose verdict value is VerdictKind::pass.
	VerdictPass VerdictKind = "pass"
	// VerdictFail is a body whose verdict value is VerdictKind::fail.
	VerdictFail VerdictKind = "fail"
	// VerdictInconclusive is a body that ran and produced no verdict value, or
	// one a definition owns with no object of the definition to run on.
	VerdictInconclusive VerdictKind = "inconclusive"
)

type VerdictStatus

type VerdictStatus int

VerdictStatus is what a check of a case decided.

const (
	// VerdictSatisfied is a check whose required conditions all held.
	VerdictSatisfied VerdictStatus = iota
	// VerdictNotSatisfied is a check with a required condition that did not hold.
	VerdictNotSatisfied
	// VerdictUndecided is a check that could not be evaluated.
	VerdictUndecided
)

func (VerdictStatus) String

func (s VerdictStatus) String() string

String names the status as a report words it.

type VerificationResult

type VerificationResult struct {
	// Verdict is the body's verdict.
	Verdict VerificationVerdict

	// Run is the case's outputs and the verdict of each objective and
	// assertion; zero when the body could not run.
	Run AnalysisResult

	// Subcases are the verdicts of the verification cases this case performs as
	// steps. The library states no roll-up of a subcase's verdict into its
	// parent's (VerificationCases::VerificationCase::subVerificationCases), so
	// each is reported on its own.
	Subcases []VerificationVerdict
}

VerificationResult is what one run of a verification case produced: the verdict of its body, what the run reported as an analysis case's run does, and the verdict of each verification subcase its body performs.

type VerificationRuns added in v0.11.0

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

VerificationRuns records the runs a report has made, so a case verifying a requirement several checks are about runs once per object it is a feature of.

type VerificationVerdict

type VerificationVerdict struct {
	// Case is the qualified name of the verification case that ran.
	Case string

	// Symbol declares the verification case.
	Symbol *symbols.Symbol

	// Kind is the VerdictKind literal the body produced.
	Kind VerdictKind

	// Detail is the message of an error verdict, or why an inconclusive one
	// decided nothing; empty for pass and fail.
	Detail string

	// Subcase marks the verdict of a case performed by another, which the
	// library states no roll-up for and which is therefore reported on its own.
	Subcase bool

	// Subject is the object the case ran as a feature of: an object of the type
	// owning it; nil for a package-level case or a run on no object.
	Subject *Instance
}

VerificationVerdict is the verdict one run of a verification case's body produced. It is reported beside the requirement-satisfaction verdicts of the same case, which it does not replace: the SysML v2 specification leaves the evaluation of a verdict unspecified, so this verdict is what running the body and the library's own PassIf calculation answer.

type Violation

type Violation struct {
	Kind ViolationKind
	// Name is the property violated, empty for a deadlock or a failure.
	Name string
	// Err is the deadlock or the failure as the executor reported it, nil for a property.
	Err error
	// Depth is how many moves the witness makes.
	Depth   int
	Witness Witness
	// Mass is the probability of the schedules reaching this violation: the sum
	// of their path masses, each the product of its picks' shares — a weighted
	// choice's stated share, an unweighted one's uniform share. It is a lower
	// bound while the report's MassBounded holds.
	Mass float64
}

Violation is one violation a schedule reached, with the schedule as its witness.

func (Violation) String

func (v Violation) String() string

String renders the violation for a report.

type ViolationError

type ViolationError struct {
	Kind      string // "constraint" or "requirement"
	Element   string // name of the element stating the condition
	What      string // "assertion" or "require condition"
	Condition string // the condition, rendered
}

ViolationError reports a condition that evaluated to false, naming the condition so a verdict says which one failed. It unwraps to ErrViolated, since it is a verdict about the model rather than a failure to evaluate.

func (*ViolationError) Error

func (e *ViolationError) Error() string

func (*ViolationError) Unwrap

func (e *ViolationError) Unwrap() error

type ViolationKind

type ViolationKind int

ViolationKind classifies what a schedule reached.

const (
	// ViolationProperty is a property evaluating false at a reached state.
	ViolationProperty ViolationKind = iota

	// ViolationFailure is a typed runtime error a move raised.
	ViolationFailure
)

func (ViolationKind) String

func (k ViolationKind) String() string

type Witness

type Witness struct {
	Objects []ObjectNamed
	Inputs  []InputTaken
	// DrawPolicy is the policy the draws were resolved under; the line is written
	// only for a fixed policy, so a random run's witness reads as before.
	DrawPolicy DrawPolicy
	// ClockStep is the step, in seconds, the run's clock ticked by; the line is
	// written only for a stepped clock, so a continuous run's witness reads as before.
	ClockStep float64
	Draws     []DrawTaken
	Choices   []ChoiceTaken
	Trace     string
	// Property names the property false at the state the schedule reaches, or
	// whose evaluation there fails as Fails says; empty for a state or a run's failure.
	Property string
	// Fails is the deadlock or failure the schedule ends in, as the executor
	// spells it — or the property's evaluation raised; empty for a state the run goes on from.
	Fails string
}

Witness is one schedule as a witness file holds it: the objects its moves name bound to their paths, the inputs the run fixes before its first move, the values its random draws took, the choices that fix the schedule as a replay follows them, and the trace the run leaves, as the trace recorder writes it.

func ParseWitness

func ParseWitness(text string) (Witness, error)

ParseWitness reads a witness as Witness.String writes it: the header of input and choice lines, after the blank line ending it the trace, exact, and after a blank line ending that the claims closing it, if any.

func (Witness) String

func (w Witness) String() string

String renders the witness as a file holds it: its objects one per line, its inputs one per line, `draws by <policy>` for a fixed draw policy, `clock steps by <seconds>` for a stepped clock, its draws one per line, its choices one per line — or `no choice points` — a blank line, the trace, and after a blank line the claims closing it: `property: <name>` for a property's, `fails: <the failure>` for a schedule ending in a failure, last.

type WitnessInputError

type WitnessInputError struct {
	Feature string
	Reason  string
}

WitnessInputError reports a witness input the run could not fix before its first move: the feature named, and why.

func (*WitnessInputError) Error

func (e *WitnessInputError) Error() string

func (*WitnessInputError) Is

func (e *WitnessInputError) Is(target error) bool

Is makes every WitnessInputError match ErrWitnessInput.

Source Files

Jump to

Keyboard shortcuts

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