opensysml

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 24 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.

README

opensysml — the public Go API

github.com/Open-MBEE/OpenSysML at client/opensysml is the Go surface of OpenSysML: parse SysML v2 models, look up symbols, evaluate expressions, instantiate parts, run actions and state machines, verify constraints and requirements, evaluate calculations, query the model, render documents, convert notations and edit source — from Go code, using the engine already linked into the calling binary. Every RPC the service answers is a method here.

go get github.com/Open-MBEE/OpenSysML@latest

Nothing else is installed: the SysML standard library is embedded in the module, and no operation shells out.

client, err := opensysml.New()
if err != nil { ... }
defer client.Close()

model, err := client.ParseFile(ctx, "vehicle.sysml")
mass, err := client.Evaluate(ctx, model, "mass", opensysml.WithSubject("Demo::sedan"))
inst, err := client.Instantiate(ctx, model, "Demo::Vehicle")

The whole surface

What you want Call
Parse one document ParseFile, ParseSource
Parse a model of several documents ParseFiles, ParseDocuments
Read the model LookupSymbol, Diagnostics
Compute with it Evaluate, Instantiate, EvaluateCalc, Calculate, RunAnalysis
Run behavior ExecuteAction, ExecuteState
Run every linearization of it ExploreAction, ExploreState, ExploreAnalysis
Play it step by step OpenSession, then Session.Instantiate, Send, Advance, Perform
Check it VerifyConstraint, VerifyRequirement, VerifySatisfaction, ValidateInstance
Choose who answers ListEngines, WithEngine, Engine, CalcEngine
Search it Query, QueryOSLC
Report on it RunDocumentQuery, RenderDocument, RenderView
Write it out Convert, ConvertFile, ConvertSource
Change its source ApplyEdits

RenderView returns ordered, typed node, edge, port and source-origin data. Ports used by connections are returned by default; pass opensysml.WithFullPorts() to include every declared port, opensysml.WithShow("edge-labels", ...) to draw optional notation elements (the result's Shown lists the ones drawn) and opensysml.WithDepth(n) to draw only n levels of nested elements below each exposed element and opensysml.WithCompartments("most") (or "ports") to fold a tree's owned members into compartment rows of their owner, each a node whose Compartment names the compartment of its Parent.

Execution and verification take the same handles the rest of the API takes:

run, err := client.ExecuteAction(ctx, model, "Demo::addFive",
	map[string]opensysml.Value{"result": opensysml.Int(10)})

verification, err := client.VerifyConstraint(ctx, model, "Demo::massBudget",
	opensysml.Against("Demo::sedan"))
if !verification.Verdict.Holds {
	// verification.Verdict.Condition names what evaluated false
}

A verdict of false is an answer about the model, not an error: a verification fails only when it could not be evaluated at all, and then it is a *VerifyError whose Reason classifies the failure. A condition the runtime could not evaluate for one subject arrives as Verdict.Undecided().

ValidateInstance builds one object of the part named and answers every assertion about it and the objects it holds — asserted constraints, requirement usages and satisfy assertions whose subject is in the tree — as a Validation: one Verdict per assertion per object, each placing its object by InstancePath (wheels[2]), and a Summary of Kind "object" that Valid() reads. Violated() lists the verdicts the model answered false, kept apart from undecided ones, and Bounded marks a walk cut short, which is not valid either.

What running a verification case's body answered is a separate answer, reported beside the satisfaction verdict rather than instead of it, by a service advertising CapabilityVerificationVerdicts. Verification.Verifications, Analysis.Verifications and Satisfaction.Verifications carry those VerificationVerdicts; because one VerifySatisfaction response can cover several requirements, each Verdict in it carries only the cases of its own RequirementID.

A trade study run through RunAnalysis reports each application of its evaluationFunction as an Evaluation in Analysis.Evaluations, in subject order, the alternative it scored an InstanceID that Analysis.Instance resolves; Analysis.Selected() is the one selectOne picked, and Tied marks another scoring the same. Reported by a service advertising CapabilityCaseEvaluations. A run that fails leaving something to inspect — an alternative it could not score after scoring others, an objective left undecided by the failure — is an *AnalysisError whose Partial keeps the outputs and evaluations it made, every verdict undecided; a request refused before the run (ReasonWrongKind for a symbol that is no case) or a failure that left nothing to report is a *VerifyError alone:

analysis, err := client.RunAnalysis(ctx, model, "Trade::lightest")
var failed *opensysml.AnalysisError
if errors.As(err, &failed) {
	analysis = failed.Partial // what the run computed before it failed
}
for _, e := range analysis.Evaluations {
	alternative := analysis.Instance(e.Arguments[0].(opensysml.InstanceID))
	// alternative.TypeSymbolID, e.Result or e.Error, e.Selected, e.Tied
}

A run resolves its choice points — several tokens steppable at once, several guards holding, several transitions enabled — under the scheduling policy WithSchedule (or Schedule, for an analysis) names: declared, reverse (the default) or seed:<n>. ExploreAction, ExploreState and ExploreAnalysis run every linearization instead and answer an Exploration: one Outcome per distinct result with the Linearizations that reached it and one run's Witness, and whether the search was Complete or which BudgetsHit ended it. WithSchedule("explore:runs=64,depth=8") sets the budget; a run that fails after it begins under some orders is an Outcome with its Error set, not a failed call. A failure to create or initialize the root executor is instead returned as an error with no exploration. FailedLinearizations counts runtime-error runs; each outcome's ProbabilityRange is nil unless a weighted model choice occurred and otherwise bounds its model-draw probability over schedulers. Scheduling choices have no probability. The single-run and exploring calls refuse each other's policies with CodeInvalidArgument, so a policy is never quietly answered by the wrong shape.

Sessions

ExecuteAction and ExecuteState run a whole behaviour and answer what it did. A Session is the interactive shape: a persistent run of one model that keeps its clock, its scheduling policy and the objects it instantiated between calls, for a debugger, a simulator's console or a game played against the model one key at a time.

session, err := opensysml.OpenSession(client, model)
defer session.Close()

hero, err := session.Instantiate("Play::hero")           // starts the machines it exhibits
err = session.SetSchedule("seed:42")                     // the dice later turns roll, the running machines' and clock's included
states, err := session.ActiveStates(hero)                // ["town"]
transitions, err := session.Transitions(hero)            // out of each active state and those enclosing it: Source, Target, Trigger, Signal or Event, Guarded
acceptance, err := session.Accepts(hero, "Play::Go", nil) // Taken(), as dispatch selects among machines; Accepted; Enabled() is whether a guard holds now
_, err = session.Send(hero, "Play::Go", nil)             // posts it, or refuses with CodeFailedPrecondition
advanced, err := session.Advance(1)                      // dispatches, completion transitions included; Choices
performed, err := session.Perform(hero, "Play::Hero::pay",
	map[string]opensysml.Value{"amount": opensysml.Int(5)}) // Outputs, Choices, Branches; TurnedAway()
value, err := session.Feature(hero, "gold")              // as the runs left it
err = session.SetFeature(hero, "gold", opensysml.Int(100))
v, err := session.Evaluate("town.shop.stick", opensysml.WithContextSymbol("Play::hero"))
members, err := session.Members("Play::Mood")            // an enumeration's literals, a package's parts

A session answers facts, never the engine's own graphs or objects: a Transition is its ends and trigger by name; an Acceptance is whether a transition accepts the signal and whether one is enabled; a Performance carries the run's outputs, its ChoicePoints (where the schedule chose, what it could have chosen, what it took) and the Branch each decision of the action's own flow left by, with TurnedAway() reading whether the opening decision took its else branch — the shape of an action that looks at its inputs and declines. Objects are InstanceID handles that Feature, SetFeature, Accepts, Send and Perform take, and Evaluate reads them where an expression names one.

A Session is not part of the Client interface, on purpose. Client is the set of RPCs the service answers, and New and Dial are held to identical answers by the conformance suite; a session is state the engine holds between calls, which the service exposes no RPC for. Rather than a Dial that answers some methods and not others, OpenSession is a separate in-process-only surface opened from a Client: a client New returned answers it, a Dial client is refused with CodeUnimplemented, and nothing is stubbed in between. The Client contract is untouched — every one of its methods still answers identically over both — and a session over the wire, if one is added, will be a set of RPCs with the same fact-shaped answers.

Misuse is refused, never a panic: a closed session answers CodeUnavailable; a signal no transition out of an active state, or a state enclosing one, accepts in any machine the object exhibits, or one whose every guard is false, CodeFailedPrecondition; an exploration policy or a negative advance CodeInvalidArgument; an unknown symbol, object or action, or a run the model fails, a *FailureError as the request-scoped calls report them. A session holds its model in the client's cache and the objects it made until Close, which releases them; closing twice is harmless, and Close on the client does not close a session opened from it, so close the session first. Its objects are bounded as the service bounds the objects it holds for queries (OPENSYSML_GRPC_MAX_HELD_OBJECTS, 10000 by default) — a call that would pass the bound answers CodeResourceExhausted — and its runs by the same step budget as ExecuteAction, each Evaluate and Perform a run of its own.

The Legend of the Red Dragon browser game is a client of this surface and nothing else: it imports only this package, compiled to WebAssembly.

PerformedBy names the object an action or state machine runs on, as sysml -action "<action> <object>" does: a part definition or usage to make an object of, or a path from one into its parts — PerformedBy("Mission::mission.vehicle") makes the mission and runs on its vehicle, inside the assembly, so a machine the vehicle exhibits hears the ground station over their connector. Each explored run makes the object anew. The option needs the performer capability.

exploration, err := client.ExploreAction(ctx, model, "Demo::race", nil)
for _, outcome := range exploration.Outcomes {
	fmt.Println(outcome.Outputs["winner"], outcome.Linearizations, outcome.Witness)
}
fmt.Println(exploration.Status()) // complete (6 runs)

Every verdict, calculation and analysis carries its Standing: the analysis engine that answered (run, explore, sweep or solve), the Strength of its evidence (observed, witnessed, bounded, proved, or not covered) and the Bounds it ran under, each marked Reached when hitting it is what stopped the run. ListEngines names the engines a service registers with the strongest strength each may claim and the question kinds it answers; WithEngine (Engine for an analysis, CalcEngine for a calculation put through Calculate) puts the question to one of them by name, to EngineAll for every engine that covers it, or to EngineAuto — the default — for the service's own choice. A named engine that refuses the question is the answer, not a fallback, and an engine the service does not register is refused with CodeInvalidArgument.

verification, err := client.VerifyConstraint(ctx, model, "Demo::Vehicle::massLight",
	opensysml.Against("Demo::sedan"), opensysml.WithEngine("run"))
fmt.Println(verification.Verdict.Standing.Engine, verification.Verdict.Standing.Strength) // run observed

An action or state machine runs on a simulation clock that starts at 0 and advances through every accept after/accept at its tokens and transitions wait on; ActionRun.FinalTime and StateRun.FinalTime are where it stood, in seconds, when the run ended, reported by a service advertising CapabilityFinalTime.

Queries are built from typed conditions rather than a string dialect, so an unsupported operator is a compile error rather than a refused call:

elements, err := client.Query(ctx, model, opensysml.Query{
	Scope:  []string{"Demo"},
	Select: []string{"name", "qualifiedName"},
	Where: opensysml.All(
		opensysml.Equals("@type", "PartUsage"),
		opensysml.Equals("name", "engine").Not(),
	),
})

Edits are typed the same way — SetValue, Rename, AddMember, AddConnection, AddSatisfy, AddRequirementConstraint, AddTransition, AddVerify, AddMetadata, AddMetadataPrefix, AddSequence, AddImport, AddDocumentation, AddComment, AddNote, Delete, Move — and either all apply, answering the edited source, or none do; the refusal arrives as an *EditError naming its kind:

result, err := client.ApplyEdits(ctx, model,
	opensysml.SetValue{Target: "Demo::sedan::mass", Value: "1200.0[SI::kg]"})

result, err = client.ApplyEdits(ctx, model, opensysml.AddConnection{
	Owner: "Demo::System", Kind: "allocation", From: "a", To: "b", Name: "alloc1",
})

result, err = client.ApplyEdits(ctx, model,
	opensysml.AddMember{
		Owner: "Demo::System", Kind: "attribute", Name: "active",
		Type: "Boolean", IsDefault: true, Value: "true",
	},
	opensysml.AddSatisfy{
		Owner: "Demo::System::safety", Requirement: "Demo::Safe", By: "Demo::System",
		Asserted: true,
	},
)

var refused *opensysml.EditError
if errors.As(err, &refused) && refused.Failure == opensysml.EditFailureDeleteReferenced {
	// refused.Referrers names what still refers to it, each with its document
}

The new member modifiers and ref/return kinds require member_modifiers; AddSatisfy and AddRequirementConstraint require satisfy_authoring and requirement_constraint_authoring, respectively, alongside authoring. AddTransition also requires authoring and transition_authoring; use AddEntryTransition to construct its entry-transition form. AddVerify writes verify <requirement>; in a verification case objective and requires authoring and verification_objective_authoring. AddMetadata writes a metadata usage with optional About, Values (MetadataValue{Feature, Value}) and shorthand @ notation; it requires authoring and metadata_authoring. AddMember.MetadataPrefixes adds #M metadata to the new declaration and requires the same capabilities. AddMetadataPrefix adds a prefix to an existing SysML declaration and requires authoring and metadata_prefix_authoring; the metadata definition resolves in that declaration's scope. AddSequence requires authoring and sequence_authoring, and writes first <ref>;, then <ref>; or then <kind> <name> : <type>; members in an action body; After names the member it follows. Action-body statements and source-end multiplicities also require action_body_statement_authoring; they use the same recursive AddSequence operation, with nested body items omitting Owner and After. An AddMember with an empty Kind writes a directed usage with no kind keyword (in x : T;) and requires implicit_parameters. AddMember.BodyExpression writes a constraint condition in { ... }, distinct from Value, which writes a feature value with = .... For calc, case, analysis, verification and use-case kinds, it writes the body's result expression. Reference-form assert and assert not members are anonymous, and post-edit analysis checks that their feature reference denotes a constraint. Constraint-body and assertion additions require constraint_body_authoring; exhibit and state subaction kinds require state_action_authoring, both alongside authoring. AddImport requires authoring and import_authoring. AddMember.Doc and AddDocumentation{Target, Body, Name, Locale, Replace} write doc /* ... */ on a new or an existing declaration and require authoring and documentation_authoring. AddComment{Owner, Body, Name, About, Locale} writes a comment element and AddNote{Target, Text} a // text line note above a declaration; both require authoring and comment_authoring.

The edited source is result.Documents, one EditedDocument per document the batch reached, under the name the model was parsed with — for a model of one document, that one. Each AppliedEdit names the Document its bytes belong to.

What a model is here

ParseFile reads the one path it is given and ParseSource the one string, and neither follows an import into a sibling file: a name declared in another file is an unresolved reference, reported as a diagnostic on the model rather than as a failed call.

A model that lives in several files is parsed as one model by ParseFiles, or by ParseDocuments for files and in-memory sources together:

model, err := client.ParseFiles(ctx, paths)

model, err := client.ParseDocuments(ctx, []opensysml.Document{
	opensysml.File("lib.sysml"),
	opensysml.Source("top.sysml", generated),
})

Each document is parsed on its own and all of them are indexed together, so an import between them resolves and every symbol of the set is one lookup, evaluation or instantiation away. Nothing is concatenated: a document keeps its own name, so a diagnostic locates itself in the file it came from, and Model.Roots holds each document's root namespace in the order given — Model.Root is the first, as it is for a one-document model. A set is cached by what is in it, so parsing the same documents again answers the same model hash.

Convert from a model handle writes one document's own notation back out, and is refused with CodeFailedPrecondition for a model of several rather than applied to one of them; convert a single document of such a set with ConvertFile or ConvertSource.

A graph notation — FormatTTL or FormatAPIJSON — spells the ids of elements that declared none from their qualified names; WithIDForm(IDFormUUID) spells them as name-based uuids under each root package instead, the library convention, and a notation target refuses the option as CodeInvalidArgument. API JSON names the standard-library elements a model uses in the Conversion's LibraryReferences (each an ID, QualifiedName and metaclass Type) rather than writing them as elements; WithLibraryStubs() restores the ownerless library stubs releases before 0.11.0 wrote, and needs the service's CapabilityConvertLibraryStubs.

ParseDocuments can relate the model it parses to one the program already holds results of: WithBaseModel(previous) has the service compare the two document by document and fill the new model's Affected with the names of the documents whose analysis, diagnostics or conversion may differ from the base's, so a program keeps what it computed for the others. The service answers every document when it cannot compare, such as for a set it has not seen before, and a base it no longer holds is not an error. The option needs CapabilityParseSourcesAffected, applies to ParseDocuments alone — ParseFile and ParseSource refuse it as CodeInvalidArgument — and a nil base is no base.

ImportData sets the feature values tabular or JSON data assigns; ImportAs names what each row is made into, ImportAsValues being the default and so far the only form, ImportDryRun() reports the assignments without changing the model, and ImportAcceptDocuments() accepts a model of several documents' edited documents as ApplyEdits does.

ApplyEdits edits the set as one model. Its operations name elements declared in the first document; ApplyDocumentEdits(ctx, model, "top.sysml", edits...) names another, and a name that is not one of the model's is CodeInvalidArgument. A rename or a cascade delete follows its references into the other documents, every document touched is re-parsed and re-analysed together, and result.Documents lists exactly the documents rewritten — so a batch that reaches one document of three answers one EditedDocument. The client marks every request as accepting documents; the service refuses a request that does not on a model of several, as it did before, so a program reading the sole-document content through an earlier client is never handed an empty one. A reference from a document the edit cannot rewrite, such as a bundled library file, refuses the edit as EditFailureReferencedElsewhere, naming it in Referrers. All of this is the CapabilityEditDocuments capability, which every service since 0.9.0 advertises: ApplyEdits and ApplyDocumentEdits require it and are refused with CodeUnimplemented by a service without it, whose answer carried the notation in the sole-document content alone — the EditResult.Content field that read it, deprecated in 0.9.0, was removed in 0.12.0.

Concurrency, contexts and lifetime

A Client is safe for concurrent use: any number of goroutines may call it, and each answer belongs to its caller. One Client per process is the intended shape — New builds and prewarms a standard-library index, which is what makes it worth keeping.

Contexts are honoured as the wire honours them. A call whose context is already done is refused with CodeCanceled or CodeDeadlineExceeded; a context that ends while a call is running withholds the answer the same way, because the engine — like a service answering a caller who stopped listening — still runs the call it started. A deadline therefore bounds how long a caller waits, not how long the engine works.

After Close, every call is refused with CodeUnavailable, and closing twice is not an error, so a deferred Close beside an explicit one is safe.

ServerInfo.Version is the version of OpenSysML linked into the binary — the module version an importing program resolved, dev when it was built from a checkout. It is informational: negotiate on capabilities.

Why in-process is the default

This is a Go repository: a Go program that imports this module already links the parser, the semantic engine and the runtime. New calls them directly — no port, no child process, no serialization round trip. It answers through the same service implementation (internal/frontend/grpc.Service) the wire transports serve, so the semantics are the service's semantics: the same content-addressed parse cache and model hashes, the same capability list, the same in-band failures, the same runtime budgets (read from the environment, as the service reads them).

Dial addresses a service the caller did not start: a shared, long-lived sysml-grpc run elsewhere, addressed explicitly ("host:50051" or "https://sysml.example.com"). It speaks the Connect protocol with protobuf bodies by default — JSON (WithJSONBody) costs an order of magnitude in encoding time on large responses and is a debugging affordance, per docs/internals/design/transport-evaluation.md. A service on an address other machines reach requires a bearer token, which WithToken sends as Authorization: Bearer on every call; without it Dial reads $OPENSYSML_GRPC_TOKEN (TokenEnv), and a call without the right token fails with CodeUnauthenticated. This package never spawns a service: a Go process that wants the engine in-process uses New, which is strictly better than a private child — the child's entire job would be to serve the code New already calls.

Errors

A call fails in exactly one of two ways, and the difference is part of the API because it is part of the wire contract:

Failure Type Test with Example
The call is refused *StatusError errors.Is(err, opensysml.CodeNotFound) an unknown model hash, an unreadable path
The answer reports a failure *FailureError errors.Is(err, opensysml.ErrFailure) an unparsable expression, an unknown symbol

A StatusError renders as opensysml: NOT_FOUND: model not found: …, naming the code canonically. StatusError.Code is the canonical gRPC status code, whichever implementation answered: in process it is the code the handler refused with; remotely it is the Connect error code, which numbers identically. A transport failure that never reached the service is CodeUnavailable. A panic in the engine does not cross the boundary: it arrives as CodeInternal.

Syntax errors are neither: parsing broken source succeeds, and the errors are Model.Diagnostics — the same shape the LSP and the wire report.

Ownership

Everything a Client returns is a copy the caller owns. In process there is no serialization boundary to force this, so it is a documented promise instead: no returned value aliases engine state, and mutating a returned Model, Symbol, Value or Instance changes nothing about the model, the cache or later answers.

Capabilities

Negotiate on names, not versions: ServerInfo.Capabilities lists what the answering implementation supports, and ServerInfo.Has checks one. A request that asks for an unavailable capability is refused with CodeUnimplemented; capabilities that describe response population instead omit the fields they name. Check the list first for an operation-specific error (the Capability* constants name the known ones). Seven capabilities are checked for you: a Complex among ExecuteAction inputs or EvaluateCalc/RunAnalysis arguments needs complex_values, an Array, Vector or VectorQuantity needs structured_values, a MeasurementRef needs measurement_refs, a Function (a calc held as a value, sent back to bind a calc-typed parameter) needs function_values, a Set needs set_values, a TensorQuantity needs tensor_values and a Metaobject (an element reflected on as an instance of its metaclass, what x meta T evaluates to) needs metaobject_values — each at the top level or nested in a sequence, set or array; a service without them would read the value as null, so the client refuses with CodeUnimplemented before sending anything. A scheduling policy is checked the same way: WithSchedule/Schedule need schedule, and the Explore* calls schedule_explore besides, since a service without them would run under the default, or run once, rather than refuse. So is an engine: WithEngine, Engine and CalcEngine naming anything but EngineAuto need engines, since a service without it would answer with whichever engine it chose. WithLibraryStubs needs convert_library_stubs and WithBaseModel needs parse_sources_affected, since a service without them would write bare library references, or parse without relating the models, instead of refusing.

A Set arrives with its elements in the service's canonical order — Booleans, then numbers, strings, quantities, enumeration literals and objects, each class in its own order — so two equal sets arrive alike, and one that lists a member twice reads as an unsupported Null naming it; a Set you send may list its elements in any order, but one listing an element twice, by Equal, is refused with CodeInvalidArgument before it is sent rather than read as one element. Set.Contains tests membership and Equal compares any two values as the service does — sets by membership, sequences in order, numbers by value, so Int(1) is Real(1) and a Complex on the real axis is its real part, exactly across the whole Int range; a Quantity by magnitude through its Term, so 1 [m] is 100 [cm] (exactly, while the magnitude is an Int and the scale a whole ratio), and one without a Term in its unit as written. A TensorQuantity carries its dimensions and one Quantity per component in row-major order, at any rank; one whose dimensions are not all positive, or whose components do not fill them, is refused with CodeInvalidArgument before it is sent. A Metaobject carries the FQN of the element it reflects on, which is its identity, and of that element's own reflective metaclass (SysML::Systems::PartUsage, never the type it was cast to); its features are read in the model rather than carried, and one you send may leave the metaclass empty to have the model's used, but one naming a metaclass that is not the element's is refused by the service.

Stability

The module is v0, so the Go compatibility promise does not yet formally bind it (see docs/project/releasing.md for how releases are cut). Within v0, this package's exported surface is what OpenSysML commits to keeping compatible:

  • Stable: Client and its operations, New, Dial, the option functions, the error model (Code, StatusError, FailureError, VerifyError, EditError, ErrFailure), and the data types they exchange. Changes will be additive.
  • Experimental: RDF conversion, whose vocabulary may change without a compatibility path — a Conversion says so in Experimental and ExperimentalNotice.

The Client interface is sealed, so adding a method is not a breaking change.

One thing is deliberately absent: generated model-ergonomics types (a Go struct per SysML definition). Models are read through Symbol, Instance and Value, which need no code generation step.

The default verification question, evaluate, evaluates conditions with the runtime that Evaluate and Instantiate use, so an in-process caller needs nothing installed for it. The holds and satisfiable questions (QuestionHolds, QuestionSatisfiable) are put to the service's solve engine, which runs an external SMT solver (z3 or cvc5) found on PATH; ListEngines reports whether one was found, and a question put to an engine that is not ready is answered with an undecided verdict naming the reason. The REPL's %check, %solve, %optimize and %explain have no RPC of their own.

Conformance

The language-independent suite in conformance/ runs through this package — not through raw stubs — as the pkg (in-process) and pkg-connect (remote) protocols of the reference runner:

make conformance-pkg
# or: go run -C tools ./cmd/conformance -protocols pkg,pkg-connect -allow-skips

Two scenarios are reported as skips, because they state a request this API's types cannot express: a parse naming no source, and a query naming no comparison operator. Every other scenario runs through this package, on both protocols.

Documentation

Overview

Package opensysml is the public Go API for OpenSysML: parse SysML v2 models, look up symbols, evaluate expressions, instantiate parts, run actions and state machines, verify constraints and requirements, evaluate calculations, query the model, render documents, convert notations and edit source. Every RPC the service answers is a method on Client.

Two implementations, one interface

New answers in process: the engine is already linked into a Go binary that imports this module, so the default implementation calls it directly — no port, no child process, no serialization. Dial answers through a sysml-grpc service someone else runs, named by an explicit address; this package never starts one. Both implement Client identically, and the conformance suite in conformance/ runs through both to hold them to it.

client, err := opensysml.New()
// or: client, err := opensysml.Dial("localhost:50051")

Models of several documents

ParseFile and ParseSource each parse one document, which reads no sibling file: a name imported from another file is an unresolved-reference diagnostic rather than an error. ParseFiles and ParseDocuments parse several documents as one model, so an import between them is satisfied and every symbol resolves across them:

model, err := client.ParseFiles(ctx, []string{"lib.sysml", "top.sysml"})

Each document keeps its own name, so a diagnostic locates itself in the file it came from, and Model.Roots holds the root namespace of each in the order parsed. The rest of the API takes such a model as it takes any other, except that an operation rewriting one document's own notation — conversion from a model handle, and editing — is refused with CodeFailedPrecondition rather than applied to one document of several.

Sessions

Every method on Client is request-scoped: ExecuteAction and ExecuteState run a whole behaviour and answer what it did. A Session is the other shape — a persistent, interactive run that keeps its clock, its scheduling policy and the objects it instantiated between calls, so a caller instantiates a part, sends its state machine a signal, performs an action on it and reads what changed, one step at a time:

session, err := opensysml.OpenSession(client, model)
hero, err := session.Instantiate("Play::hero")
acceptance, err := session.Accepts(hero, "Play::Go", nil)
_, err = session.Send(hero, "Play::Go", nil)
advanced, err := session.Advance(1)
performed, err := session.Perform(hero, "Play::Hero::pay", inputs)

A Session is deliberately not part of the Client interface. Client is the set of RPCs the service answers, held to identical answers from New and Dial by the conformance suite; a session is state the engine holds between calls, which the service exposes no RPC for. Rather than a Dial that answers some methods and not others, OpenSession is a separate, in-process-only surface: it is opened from a Client, so a program reaches it through the same handle and model it uses for everything else, but only a client New returned can answer it, and a Dial client is refused with CodeUnimplemented. What a Session answers is facts — the transitions out of the active states, and the states enclosing them, of every machine an object exhibits and what fires them, whether a signal's guard holds now, the choice points a run made, whether an action's opening decision turned its caller away — never the engine's own graphs or objects, so the boundary the rest of the package keeps holds here too.

Answers, verdicts and refusals

Operations that ask something of the model answer what it says rather than treating an unwelcome answer as an error. A constraint that does not hold is a Verdict with Holds false; only a verification that could not be evaluated at all is an error, a *VerifyError whose Reason classifies it. A set of edits either all apply or none do, and a refusal is an *EditError naming its kind.

Concurrency, contexts and lifetime

A Client is safe for concurrent use from any number of goroutines. A call whose context is already done is refused with CodeCanceled or CodeDeadlineExceeded, and a context that ends while a call is running withholds its answer the same way — the engine, like a service, still runs the call it started. After Close every call is refused with CodeUnavailable, and closing twice is not an error.

Errors

A call fails in one of two documented ways, and the difference is part of the API because it is part of the wire contract:

  • A refused call is a *StatusError carrying the canonical gRPC status code (rendered by its canonical name, as in "opensysml: NOT_FOUND: …"), whichever implementation answered. errors.Is(err, CodeNotFound) tests the code: an unknown model hash, for example, is CodeNotFound.
  • A failure the service reports inside a successful answer — an unparsable expression, an unknown symbol, a failed instantiation — is a *FailureError, matched by errors.Is(err, ErrFailure), carrying the service's message and any diagnostics.

A panic in the engine does not cross this boundary: the in-process implementation reports it as a *StatusError with CodeInternal, the status the wire would answer for a crashed handler.

Ownership

Everything a Client returns is a copy the caller owns. The in-process implementation has no serialization boundary, so this is a promise, not a consequence: no returned value aliases engine state, and mutating one changes nothing about the model, the cache or later answers.

Capabilities

Negotiate on ServerInfo.Capabilities, not on versions. Capability-gated requests are refused when unavailable, while response-population capabilities omit the fields they name. ServerInfo.Has provides the client-side preflight.

Stability

The module is v0, so the Go compatibility promise does not yet bind it. Within v0, the surface of this package is what OpenSysML commits to keeping compatible: see the package README for the statement. RDF conversion is experimental — a Conversion says so — and generated model-ergonomics types are deliberately absent, models being read through Symbol, Instance and Value.

The default verification question, evaluate, evaluates conditions with the same runtime Evaluate and Instantiate use, so an in-process caller needs nothing installed for it. QuestionHolds and QuestionSatisfiable are put to the service's solve engine, which runs an external SMT solver (z3 or cvc5) found on PATH; ListEngines reports whether one was found.

Example

Example parses a model, evaluates an expression against an object, and instantiates a definition — all in process.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/Open-MBEE/OpenSysML/client/opensysml"
)

func main() {
	client, err := opensysml.New()
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
	ctx := context.Background()

	model, err := client.ParseSource(ctx, `package Demo {
		part def Vehicle {
			attribute mass = 1500.0;
		}
		part sedan : Vehicle {
			attribute :>> mass = 1800.0;
		}
	}`)
	if err != nil {
		log.Fatal(err)
	}

	mass, err := client.Evaluate(ctx, model, "mass", opensysml.WithSubject("Demo::sedan"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("sedan mass: %v\n", mass)

	instantiation, err := client.Instantiate(ctx, model, "Demo::Vehicle")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("instance of: %s\n", instantiation.Root.TypeSymbolID)
}
Output:
sedan mass: 1800
instance of: Demo::Vehicle

Index

Examples

Constants

View Source
const (
	// EngineAuto lets the service pick the engine, which sending no engine does.
	EngineAuto = "auto"
	// EngineAll puts the question to every engine that covers it and composes
	// their answers.
	EngineAll = "all"
)

The engine selections every call accepts beside an engine's name.

View Source
const (
	CapabilityTypeFacts                      = sysmlgrpc.CapabilityTypeFacts
	CapabilityConvert                        = sysmlgrpc.CapabilityConvert
	CapabilityMigrate                        = sysmlgrpc.CapabilityMigrate
	CapabilityVerification                   = sysmlgrpc.CapabilityVerification
	CapabilityVerificationQuestions          = sysmlgrpc.CapabilityVerificationQuestions
	CapabilityVerificationArguments          = sysmlgrpc.CapabilityVerificationArguments
	CapabilityQuery                          = sysmlgrpc.CapabilityQuery
	CapabilityOSLCQuery                      = sysmlgrpc.CapabilityOSLCQuery
	CapabilityDocumentQuery                  = sysmlgrpc.CapabilityDocumentQuery
	CapabilityRenderDocument                 = sysmlgrpc.CapabilityRenderDocument
	CapabilityRenderView                     = sysmlgrpc.CapabilityRenderView
	CapabilityExportGraphs                   = sysmlgrpc.CapabilityExportGraphs
	CapabilityImportData                     = sysmlgrpc.CapabilityImportData
	CapabilityCompareResults                 = sysmlgrpc.CapabilityCompareResults
	CapabilityCheck                          = sysmlgrpc.CapabilityCheck
	CapabilityEnumValues                     = sysmlgrpc.CapabilityEnumValues
	CapabilityEvaluateSubject                = sysmlgrpc.CapabilityEvaluateSubject
	CapabilitySymbolAttributes               = sysmlgrpc.CapabilitySymbolAttributes
	CapabilityUnsetValue                     = sysmlgrpc.CapabilityUnsetValue
	CapabilityFeatureValues                  = sysmlgrpc.CapabilityFeatureValues
	CapabilityApplyEdits                     = sysmlgrpc.CapabilityApplyEdits
	CapabilityAuthoring                      = sysmlgrpc.CapabilityAuthoring
	CapabilityConnectionAuthoring            = sysmlgrpc.CapabilityConnectionAuthoring
	CapabilitySatisfyAuthoring               = sysmlgrpc.CapabilitySatisfyAuthoring
	CapabilityRequirementConstraintAuthoring = sysmlgrpc.CapabilityRequirementConstraintAuthoring
	CapabilityMemberModifiers                = sysmlgrpc.CapabilityMemberModifiers
	CapabilityTransitionAuthoring            = sysmlgrpc.CapabilityTransitionAuthoring
	CapabilityVerificationObjectiveAuthoring = sysmlgrpc.CapabilityVerificationObjectiveAuthoring
	CapabilityMetadataAuthoring              = sysmlgrpc.CapabilityMetadataAuthoring
	CapabilityMetadataPrefixAuthoring        = sysmlgrpc.CapabilityMetadataPrefixAuthoring
	CapabilitySequenceAuthoring              = sysmlgrpc.CapabilitySequenceAuthoring
	CapabilityActionBodyStatementAuthoring   = sysmlgrpc.CapabilityActionBodyStatementAuthoring
	CapabilityImplicitParameters             = sysmlgrpc.CapabilityImplicitParameters
	CapabilityConstraintBodyAuthoring        = sysmlgrpc.CapabilityConstraintBodyAuthoring
	CapabilityStateActionAuthoring           = sysmlgrpc.CapabilityStateActionAuthoring
	CapabilityImportAuthoring                = sysmlgrpc.CapabilityImportAuthoring
	CapabilityDocumentationAuthoring         = sysmlgrpc.CapabilityDocumentationAuthoring
	CapabilityCommentAuthoring               = sysmlgrpc.CapabilityCommentAuthoring
	CapabilityEditDocuments                  = sysmlgrpc.CapabilityEditDocuments
	CapabilityInlineLanguage                 = sysmlgrpc.CapabilityInlineLanguage
	CapabilityStrictConformance              = sysmlgrpc.CapabilityStrictConformance
	CapabilityParseSources                   = sysmlgrpc.CapabilityParseSources
	CapabilityComplexValues                  = sysmlgrpc.CapabilityComplexValues
	CapabilityStructuredValues               = sysmlgrpc.CapabilityStructuredValues
	CapabilityMeasurementRefs                = sysmlgrpc.CapabilityMeasurementRefs
	CapabilityFunctionValues                 = sysmlgrpc.CapabilityFunctionValues
	CapabilitySetValues                      = sysmlgrpc.CapabilitySetValues
	CapabilityTensorValues                   = sysmlgrpc.CapabilityTensorValues
	CapabilityMetaobjectValues               = sysmlgrpc.CapabilityMetaobjectValues
	CapabilityDiagnosticCodes                = sysmlgrpc.CapabilityDiagnosticCodes
	CapabilitySchedule                       = sysmlgrpc.CapabilitySchedule
	CapabilityScheduleExplore                = sysmlgrpc.CapabilityScheduleExplore
	CapabilityVerificationVerdicts           = sysmlgrpc.CapabilityVerificationVerdicts
	CapabilityCaseEvaluations                = sysmlgrpc.CapabilityCaseEvaluations
	CapabilityFinalTime                      = sysmlgrpc.CapabilityFinalTime
	CapabilityPerformer                      = sysmlgrpc.CapabilityPerformer
	CapabilityRuns                           = sysmlgrpc.CapabilityRuns
	CapabilitySelfCheck                      = sysmlgrpc.CapabilitySelfCheck
	CapabilityRecordRun                      = sysmlgrpc.CapabilityRecordRun
	CapabilityStateTrace                     = sysmlgrpc.CapabilityStateTrace
	CapabilityActionTrace                    = sysmlgrpc.CapabilityActionTrace
	CapabilityEngines                        = sysmlgrpc.CapabilityEngines
	CapabilityUndeterminedValue              = sysmlgrpc.CapabilityUndeterminedValue
	CapabilityBigIntValues                   = sysmlgrpc.CapabilityBigIntValues
	CapabilityRationalValues                 = sysmlgrpc.CapabilityRationalValues
	CapabilityConvertDocuments               = sysmlgrpc.CapabilityConvertDocuments
	CapabilityConvertCompact                 = sysmlgrpc.CapabilityConvertCompact
	CapabilityConvertCheckDiagnostics        = sysmlgrpc.CapabilityConvertCheckDiagnostics
	CapabilityConvertLibraryReferences       = sysmlgrpc.CapabilityConvertLibraryReferences
	CapabilityConvertLibraryStubs            = sysmlgrpc.CapabilityConvertLibraryStubs
	CapabilityParseSourcesAffected           = sysmlgrpc.CapabilityParseSourcesAffected
	CapabilityRenderDocumentFileName         = sysmlgrpc.CapabilityRenderDocumentFileName
)

Capability names a client can require of a ServerInfo, re-stated from the service so negotiating on them needs no other import. Capabilities are only ever added, never renamed or removed with their behaviour intact.

View Source
const (
	SeverityError   = "error"
	SeverityWarning = "warning"
	SeverityInfo    = "info"
)

The severities a Diagnostic reports.

View Source
const (
	// QuestionEvaluate evaluates the constraint as verification always has.
	QuestionEvaluate = "evaluate"
	// QuestionHolds asks whether the claim holds for every free assignment.
	QuestionHolds = "holds"
	// QuestionSatisfiable asks whether any free assignment satisfies the claim.
	QuestionSatisfiable = "satisfiable"
)

Question names the question a verify call asks: the evaluation of the declared or held values, the claim holding for every assignment the free features can take, or one assignment satisfying it. Questions other than QuestionEvaluate ask the service's solvers, which answer decided or leave the verdict undecided.

View Source
const (
	// NoteAssumedOne marks a feature read as holding one value or object while
	// only the default `0..*` multiplicity governs it.
	NoteAssumedOne = "assumed_one"
	// NoteUncovered marks an object-holding feature whose own assertions the
	// question does not state.
	NoteUncovered = "uncovered"
)

Note kinds, as the service spells them.

View Source
const ChoiceDecisionBranch = "decision branch"

ChoiceDecisionBranch is the Kind of a ChoicePoint made at a decision node.

View Source
const ImportAsValues = "values"

ImportAsValues makes each row set the features of the element it names; the default and, so far, the only form the service supports.

View Source
const TokenEnv = "OPENSYSML_GRPC_TOKEN" // #nosec G101 -- a variable name, not a credential

TokenEnv is the environment variable Dial reads a bearer token from when WithToken names none; the Python, Node, Java and Rust clients read the same.

Variables

View Source
var ErrFailure = errors.New("opensysml: the call was answered and the answer reports a failure")

ErrFailure is the errors.Is target for every FailureError: a call the service answered, whose answer reports a failure.

Functions

func CellText added in v0.4.2

func CellText(cell Cell) string

CellText renders one cell value as a report writes it, the way the CLI's document tables do.

func Equal added in v0.7.0

func Equal(a, b Value) bool

Equal reports whether two values are the same value to the model, as the service judges a Set's membership: numbers by value, so a whole Real is the Int of its value and a Complex on the real axis is its real part, exactly across the whole Int range; a Sequence's order counts and a Set's does not, nor does a member it lists twice; a Quantity is one with any commensurable quantity of the same magnitude over their base units, so 1 m is 100 cm, while one carrying no reduction is compared in its unit as written; a MeasurementRef is one reduction at one scale however spelt, except that a named unit of dimension one is only its own declaration (rad is not sr); an EnumLiteral is its LiteralID, whatever else describes it; a Null is one whatever its reason, and one with an empty Sequence or Set, the model's absent value however spelt; and a nil Value equals only another nil.

Types

type Acceptance added in v0.9.0

type Acceptance struct {
	// Accepted reports whether a transition out of an active state of a taking
	// machine is triggered by the signal, whatever its guard. A signal only
	// resuming a do behavior is not Accepted.
	Accepted bool
	// Fires lists the transitions that would fire, taking machine by taking
	// machine in exhibit order, each machine's in the order they would.
	Fires []Transition
	// Resumes names the states whose do behavior the signal would resume.
	Resumes []string
}

Acceptance is what dispatching a signal to an object would do now, read from the machines dispatch would let take it, as Advance does: a machine yields a signal it would only drop to a sibling that would fire on it. Where several would take it, the schedule's due order decides which consumes it.

func (*Acceptance) Enabled added in v0.9.0

func (a *Acceptance) Enabled() bool

Enabled reports whether the machine would do something with the signal: a transition fires, or the signal resumes a state. An accepted signal that is not enabled is one whose every transition's guard is false.

func (*Acceptance) Taken added in v0.9.0

func (a *Acceptance) Taken() bool

Taken reports whether a machine would take the signal at all, whether to fire, resume, or drop it because every guard is false.

type ActionRun added in v0.4.2

type ActionRun struct {
	// Outputs are the action's output parameters by name, empty for an action
	// that produces none.
	Outputs map[string]Value
	// Performer is the attributes the object the action ran on holds when the
	// run ends, keyed as an explored Outcome's Outputs key them ("this.level");
	// empty without PerformedBy.
	Performer map[string]Value
	// FinalTime is the run's simulation clock when it ended, in seconds from
	// the 0 it started at; 0 from a service without CapabilityFinalTime.
	FinalTime float64
	// Trace is the run's records (token steps, waits, accepts, decisions,
	// assignments, completion) when requested with WithTrace.
	Trace []DocumentEvent
	// TraceDropped is the number of oldest trace records the service discarded.
	TraceDropped int
	// Diagnostics the execution reported.
	Diagnostics []Diagnostic
}

ActionRun is what one action execution produced.

type AddComment added in v0.9.2

type AddComment struct {
	// Owner is the namespace receiving the comment; empty is the document root.
	Owner string
	// Body is the comment text, read back exactly as Comment::body; it may not
	// contain `*/`, which closes a comment, or a carriage return.
	Body string
	// Name is the comment's optional declared name.
	Name string
	// About are the optional annotated elements, by qualified name.
	About []string
	// Locale is the optional locale, written as `locale "..."`.
	Locale string
}

AddComment inserts `comment [name] [about a, b] [locale "..."] /* ... */` where a new member of Owner goes, opening a body for one ended by `;`.

type AddConnection added in v0.9.2

type AddConnection struct {
	// Owner is the namespace to receive the usage; empty is the document root.
	Owner string
	// Kind is the written connection kind, such as "allocation" or "flow".
	Kind string
	// From is the first feature reference, written as notation.
	From string
	// To is the second feature reference, written as notation.
	To string
	// Name is the optional declared identifier.
	Name string
	// Type is an optional typing target.
	Type string
}

AddConnection inserts a connection-like usage into a namespace or document root.

type AddDocumentation added in v0.9.2

type AddDocumentation struct {
	// Target is the documented declaration, by qualified name.
	Target string
	// Body is the documentation text, read back exactly as Documentation::body;
	// it may not contain `*/`, which closes a comment, or a carriage return.
	Body string
	// Name is the documentation's optional declared name.
	Name string
	// Locale is the optional locale, written as `locale "..."`.
	Locale string
	// Replace rewrites the one documentation Target owns instead of refusing.
	Replace bool
}

AddDocumentation adds `doc /* ... */` as the first body member of an existing declaration, opening a body for one ended by `;`.

type AddImport added in v0.9.2

type AddImport struct {
	// Owner is the namespace receiving the import; empty is the document root.
	Owner string
	// Visibility is "private", "public" or "protected"; empty writes "private".
	Visibility string
	// Target is the imported qualified name, optionally rooted "$::", suffixed
	// "::*" for a namespace import.
	Target string
	// Recursive writes "::**" to import recursively.
	Recursive bool
	// All writes "import all" to import non-public members too.
	All bool
	// Filters are filter conditions, each written as "[<expression>]".
	Filters []string
}

AddImport inserts an import declaration into a namespace body or the document root.

type AddMember added in v0.4.2

type AddMember struct {
	// Owner is the namespace to receive the declaration; empty is the document root.
	Owner string
	// Kind is the written declaration kind, such as "part def" or "class".
	Kind string
	// Name is the declared identifier.
	Name string
	// Type is an optional type target for a usage, written as notation.
	Type string
	// Multiplicity is optional and includes its brackets, such as "[0..*]".
	Multiplicity string
	// Value is an optional value expression, written as notation.
	Value string
	// Specializes are optional specialization targets for a definition.
	Specializes []string
	// IsAbstract declares the definition or usage abstract.
	IsAbstract bool
	// Redefines are optional redefinition targets for a usage.
	Redefines []string
	// IsDefault writes the value with the default assignment keyword.
	IsDefault bool
	// Direction is an optional usage direction: "in", "out" or "inout".
	Direction string
	// MetadataPrefixes are metadata types prefixed to the new member with #.
	MetadataPrefixes []string
	// BodyExpression is the optional condition stated in a constraint-kind member's body.
	BodyExpression string
	// Doc is optional documentation body text, written as the declaration's
	// first body member `doc /* ... */` that reads back as exactly this text.
	Doc string
}

AddMember inserts a declaration into a namespace or the document root.

type AddMetadata added in v0.9.2

type AddMetadata struct {
	// Owner is the namespace receiving the metadata usage; empty is the document root.
	Owner string
	// MetadataType is the metadata definition reference.
	MetadataType string
	// Name is the optional usage name.
	Name string
	// About are optional references annotated by this usage.
	About []string
	// Values are the metadata feature bindings.
	Values []MetadataValue
	// Shorthand writes the usage with @ instead of metadata.
	Shorthand bool
}

AddMetadata inserts a metadata usage with optional about references and values.

type AddMetadataPrefix added in v0.9.2

type AddMetadataPrefix struct {
	// Target is the declaration to annotate, by its qualified name.
	Target string
	// MetadataType is the metadata definition reference.
	MetadataType string
}

AddMetadataPrefix adds a metadata prefix to an existing declaration.

type AddNote added in v0.9.2

type AddNote struct {
	// Target is the declaration the note precedes, by qualified name.
	Target string
	// Text is the one line of note text; it may not contain a line break.
	Text string
}

AddNote writes the line note `// text` on its own line above a declaration. A note is lexical trivia, not a model element.

type AddRequirementConstraint added in v0.9.2

type AddRequirementConstraint struct {
	// Owner is the requirement-like namespace receiving the constraint.
	Owner string
	// Kind is "require" or "assume".
	Kind string
	// Expression is the required constraint expression.
	Expression string
	// Name is the optional constraint name.
	Name string
}

AddRequirementConstraint inserts a require or assume constraint.

type AddSatisfy added in v0.9.2

type AddSatisfy struct {
	// Owner is the package or body receiving the usage.
	Owner string
	// Requirement is the requirement feature reference.
	Requirement string
	// By is the optional satisfying feature reference.
	By string
	// Asserted marks the usage asserted.
	Asserted bool
	// Negated marks the usage negated.
	Negated bool
}

AddSatisfy inserts a satisfy usage into any package or body that admits behavior usages.

type AddSequence added in v0.9.2

type AddSequence struct {
	// Owner is the action definition or usage receiving the member.
	Owner string
	// Keyword is "first", "then", "", "if" or "else".
	Keyword string
	// Ref is the node a bare `first <ref>;`/`then <ref>;` names; empty when
	// the `then` declares a member instead.
	Ref string
	// MemberKind is the action-body item kind, or a kind declared by `then`.
	MemberKind string
	// MemberName is the optional declared name of the `then`-declared member.
	MemberName string
	// Type is an optional typing target of the `then`-declared member.
	Type string
	// After names the body member the new member follows; empty appends it
	// at the end of the body.
	After string
	// Condition, Value, Target, Via, Until and Parameter describe the new
	// action-body statement fields.
	Condition    string
	Value        string
	Target       string
	Via          string
	Until        string
	Parameter    string
	Multiplicity string
	// Body and Else are recursively authored items; nested items have empty
	// Owner and After.
	Body []AddSequence
	Else []AddSequence
}

AddSequence inserts a succession or action-body statement into an action body (SysML.xtext:1607 ActionBodyParameter, 1442 AcceptNode, 1499 SendNode, 1535 AssignmentNode, 1596 IfNode, 1615 WhileLoopNode, 1624 ForLoopNode, 1641 TerminateNode, 1703 TargetSuccession, 1708 GuardedTargetSuccession, 1714 DefaultTargetSuccession; formal/2026-03-02).

type AddTransition added in v0.9.2

type AddTransition struct {
	// Owner is the state definition or usage receiving the transition.
	Owner string
	// Name is the optional transition name.
	Name string
	// Source is the source feature reference; empty only for an entry transition.
	Source string
	// Target is the target feature reference.
	Target string
	// Trigger is optional text after `accept`.
	Trigger string
	// Guard is an optional boolean expression after `if`.
	Guard string
	// Effect is optional effect text after `do`.
	Effect string
	// Initial writes an entry transition instead of a regular transition.
	Initial bool
}

AddTransition inserts a state transition or entry transition into a state body.

func AddEntryTransition added in v0.9.2

func AddEntryTransition(owner, target string) AddTransition

AddEntryTransition constructs an entry transition to target in owner.

type AddVerify added in v0.9.2

type AddVerify struct {
	// Owner is the verification case or objective receiving the verify usage.
	Owner string
	// Requirement is the requirement reference to verify.
	Requirement string
}

AddVerify inserts a verify usage into a verification case objective.

type Advancement added in v0.9.0

type Advancement struct {
	// From and To are the clock before and after.
	From, To float64
	// Events dispatched and Steps run while advancing.
	Events, Steps int64
	// Choices the runs made while advancing.
	Choices []ChoicePoint
	// Diagnostics the runs raised.
	Diagnostics []Diagnostic
}

Advancement is what advancing the clock did.

type Analysis added in v0.6.0

type Analysis struct {
	// 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 []CalcOutput
	// Verdicts are the case's objectives, in order, then the assertions in its
	// body. Kind is "objective" or "assertion".
	Verdicts []Verdict
	// Verifications are the verdicts the bodies of the case and of the
	// verification cases it performs produced, empty for an analysis case.
	Verifications []VerificationVerdict
	// Evaluations are the applications the run made of the case's own calcs, in
	// the order made: for a trade study, its evaluationFunction applied to each
	// alternative in subject order. Empty for a service not advertising
	// CapabilityCaseEvaluations.
	Evaluations []Evaluation
	// Instances are the objects the run reported: those reachable from the
	// subject, including it, and those the outputs and evaluations refer to.
	Instances []*Instance
	// Standing is how strongly the run's answer stands: the engine that
	// answered, the strength of its evidence and the bounds it ran under.
	Standing Standing
	// Diagnostics the run reported.
	Diagnostics []Diagnostic
	// ToolDryRun is the external tool call a run under ToolDryRun previewed
	// instead of making; nil otherwise.
	ToolDryRun *ToolDryRun
}

Analysis is what one run of an analysis case produced.

func (*Analysis) Holds added in v0.6.0

func (a *Analysis) Holds() bool

Holds reports whether every objective and assertion was decided and held. A case stating none holds trivially.

func (*Analysis) Instance added in v0.7.0

func (a *Analysis) Instance(id InstanceID) *Instance

Instance resolves an InstanceID an output, a verdict or an evaluation referred to, nil when the run reported no such object.

func (*Analysis) Output added in v0.6.0

func (a *Analysis) Output(name string) (Value, bool)

Output is the value of the named output, and whether the case reported one.

func (*Analysis) Selected added in v0.7.0

func (a *Analysis) Selected() []Evaluation

Selected are the evaluations of the alternatives the case selected, in the order made; none for a case that selected nothing.

type AnalysisError added in v0.7.0

type AnalysisError struct {
	VerifyError
	// Partial is what the run left: the outputs and evaluations made, the
	// objects they name, each verdict undecided.
	Partial *Analysis
}

AnalysisError is a run of an analysis case that failed leaving something to inspect: the evaluations a trade study made before an alternative failed, the outputs computed before one failed, and each objective and required assertion undecided with the failure as its reason — as an unbound subject leaves an objective. It is a VerifyError, so errors.As recovers one and errors.Is(err, ErrFailure) matches. A request refused before the run, or a failure that left nothing to report, is a *VerifyError alone: its Reason says why, ReasonWrongKind for a symbol that is no case.

func (*AnalysisError) Unwrap added in v0.7.0

func (e *AnalysisError) Unwrap() error

Unwrap exposes the classified failure, so errors.As recovers a *VerifyError and, through it, a *FailureError.

type AnalysisOption added in v0.6.0

type AnalysisOption func(*analysisOptions)

AnalysisOption configures RunAnalysis.

func Argument added in v0.6.0

func Argument(name string, value Value) AnalysisOption

Argument binds the input named, which may be a defaulted one or the subject.

func Arguments added in v0.6.0

func Arguments(values ...Value) AnalysisOption

Arguments bind the case's non-subject inputs in declaration order, after any given earlier.

func Engine added in v0.8.0

func Engine(engine string) AnalysisOption

Engine names the engine that answers an analysis, as WithEngine does for a verification. Requires the engines capability, checked before anything is sent.

func Schedule added in v0.7.0

func Schedule(policy string) AnalysisOption

Schedule names the scheduling policy the actions the case performs resolve their choice points under, as WithSchedule does for ExecuteAction. Requires the schedule capability. An exploring spelling belongs to ExploreAnalysis, which requires schedule_explore too.

func Subject added in v0.6.0

func Subject(symbolID string) AnalysisOption

Subject names a part or usage to instantiate as the case's subject, for a case whose usage binds none or to run one against another object. It is what Against is to VerifyRequirement.

func WithToolDryRun added in v0.11.0

func WithToolDryRun() AnalysisOption

WithToolDryRun runs the case up to its first external tool call and previews it in Analysis.ToolDryRun instead of making it, as sysml -tool-dry-run does.

type AppliedEdit added in v0.4.2

type AppliedEdit struct {
	// Index is the edit's position in the request, so an answer maps back to its ask.
	Index int
	// Target is the element edited, as the request named it.
	Target string
	// Document is the document the bytes belong to, named as in EditedDocument.
	Document string
	// Offset and Length are the bytes replaced; Length is zero for an insertion.
	Offset int
	Length int
	// OldText is what was there, empty for an insertion; NewText what was written.
	OldText string
	NewText string
}

AppliedEdit is one byte range of the original source an edit replaced.

type Array added in v0.6.0

type Array struct {
	// Dimensions are the positive extents, one per rank.
	Dimensions []int64
	// Elements fill the dimensions in row-major order.
	Elements []Value
}

Array is a Collections::Array: its elements in row-major order under its dimensions. Its rank is the number of dimensions; an array of rank 0 holds one element. Elements are Values, so an array of quantities or of arrays is one as such.

func (Array) String added in v0.6.0

func (a Array) String() string

String renders the array as SysML formats it: `Array(2, 2)[1, 2, 3, 4]`.

type Attribute

type Attribute struct {
	Name string
	Type string
	// Value is the declared value, nil when none is declared.
	Value Value
	Unit  string
}

Attribute is one attribute of a symbol, with its declared value.

type BigInt added in v0.10.0

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

BigInt is an integer value beyond int64: KerML Integers are unbounded. An integer within int64 is always an Int, never a BigInt; NewInteger picks.

func (BigInt) Int added in v0.10.0

func (b BigInt) Int() *big.Int

Int returns a copy of the integer.

func (BigInt) String added in v0.10.0

func (b BigInt) String() string

String spells the integer in full decimal.

type Binding added in v0.4.2

type Binding struct {
	Parameter string
	Values    []Cell
}

Binding binds one entry parameter of a document query. Several values bind a nonscalar parameter.

func Bind added in v0.4.2

func Bind(parameter string, values ...Cell) Binding

Bind is a binding of one parameter to the values given.

type Bool

type Bool bool

Bool is a boolean value.

type Bound added in v0.8.0

type Bound struct {
	// Name is the bound's name as the budget spells it: "runs", "depth", "steps".
	Name string
	// Limit is the bound's value.
	Limit int64
	// Reached is true when the run stopped at the limit, which lowers the
	// answer's strength.
	Reached bool
}

Bound is one bound an engine's answer ran under, with whether reaching it was what stopped the run.

type Branch added in v0.9.0

type Branch struct {
	// Decision names the decision node, "" when it is anonymous.
	Decision string
	// Target names the node the branch led to.
	Target string
	// Else reports the branch was the decision's `else`, taken when no guarded
	// branch was.
	Else bool
	// Opening reports the decision is the action's gate: the first decision
	// its start leads to with no other choice on the way.
	Opening bool
}

Branch is one way a performance left a decision node of the action's own flow — not of the actions it called.

type CalcOption added in v0.8.0

type CalcOption func(*calcOptions)

CalcOption configures Calculate.

func CalcArguments added in v0.8.0

func CalcArguments(values ...Value) CalcOption

CalcArguments bind the calculation's inputs in declaration order, after any given earlier; none evaluates a calc usage from its own members.

func CalcEngine added in v0.8.0

func CalcEngine(engine string) CalcOption

CalcEngine names the engine that answers the calculation, as `sysml -engine` spells it: an engine's name, EngineAuto or EngineAll. Requires the engines capability, checked before anything is sent.

type CalcOutput added in v0.4.2

type CalcOutput struct {
	Name  string
	Value Value
}

CalcOutput is one output feature a calc usage computed.

type Calculation added in v0.4.2

type Calculation struct {
	// Result is what an invocation returned, nil when Outputs carries the answer.
	Result Value
	// Outputs are a calc usage's output features in declaration order, empty for
	// an invocation with arguments.
	Outputs []CalcOutput
	// Standing is how strongly the calculation stands: the engine that answered,
	// the strength of its evidence and the bounds it ran under.
	Standing Standing
	// Diagnostics the calculation reported.
	Diagnostics []Diagnostic
}

Calculation is what one calculation computed: the value an invocation returned, or the output features a calc usage evaluated from its own members.

type CaseStatistic added in v0.11.0

type CaseStatistic struct {
	Statistic, Of, Tool, Run, Difference string
}

CaseStatistic is one statistic: which, where the case declares it, the tool's value, the runs' and their relative difference.

type CaseStatistics added in v0.11.0

type CaseStatistics struct {
	Analysis string
	Rows     []CaseStatistic
	Notes    []string
}

CaseStatistics compares the statistics a Simulation::MonteCarlo case declares with the tool's, one row per statistic.

type Cell added in v0.4.2

type Cell interface {
	// contains filtered or unexported methods
}

Cell is one typed document-query value: Element, Object, String, Int, Real, Bool, Quantity, Infinity, DocumentVerdict, DocumentState or DocumentEvent. A type switch over them is exhaustive.

type Check added in v0.11.0

type Check struct {
	// Verdict is "holds", "fails" or "undecided".
	Verdict string
	// Lines is the report as `sysml -check-property` prints it.
	Lines []string
	// Search is the explicit-state search's statistics, nil for a symbolic answer.
	Search *CheckSearch
	// Violations is each property, deadlock or failure witnessed.
	Violations []CheckViolation
	// Divergences is each feature whose final value the schedule decided.
	Divergences []CheckDivergence
	// Finals is each final outcome of an exhaustive search.
	Finals []CheckFinal
	// Claim is the symbolic engine's claim; FreeInputs the inputs it ranged
	// over and Assumptions what it assumed.
	Claim       string
	FreeInputs  []string
	Assumptions []string
	// Witness and Contrast are the symbolic engine's witness and counter-witness.
	Witness  *CheckWitness
	Contrast *CheckWitness
	// Standing is the engine's name, strength and the bounds it ran under.
	Standing Standing
	// Reason says why the verdict is undecided, when it is.
	Reason string
}

Check is what CheckBehavior answers: the verdict over every schedule of a behavior with each violation, divergence and final outcome witnessed.

func (*Check) String added in v0.11.0

func (c *Check) String() string

String renders the check as its report lines.

type CheckDivergence added in v0.11.0

type CheckDivergence struct {
	Feature string
	Values  []CheckDivergentValue
}

CheckDivergence is a feature whose final value the schedule decides.

type CheckDivergentValue added in v0.11.0

type CheckDivergentValue struct {
	Value   string
	Witness *CheckWitness
}

CheckDivergentValue is one final value a feature reaches and its witness.

type CheckFinal added in v0.11.0

type CheckFinal struct {
	Outcome string
	Values  map[string]string
	Witness *CheckWitness
}

CheckFinal is one final outcome of an exhaustive search.

type CheckOption added in v0.11.0

type CheckOption func(*checkOptions)

CheckOption configures CheckBehavior.

func CheckAssume added in v0.11.0

func CheckAssume(names ...string) CheckOption

CheckAssume names constraints or requirements the symbolic engine assumes.

func CheckBounds added in v0.11.0

func CheckBounds(depth, states, unroll int32, timeout float64) CheckOption

CheckBounds limits the search: moves per schedule, states visited, loop unrollings and seconds; zero leaves each at the engine's default.

func CheckDiverge added in v0.11.0

func CheckDiverge(features ...string) CheckOption

CheckDiverge names features whose final value the schedule may decide.

func CheckEngine added in v0.11.0

func CheckEngine(name string) CheckOption

CheckEngine selects the engine asked: "check" (the default), "smt" or one ListEngines names.

func CheckFreeInputs added in v0.11.0

func CheckFreeInputs(names ...string) CheckOption

CheckFreeInputs leaves inputs free for the symbolic engine to range over.

func CheckInputs added in v0.11.0

func CheckInputs(inputs map[string]Value) CheckOption

CheckInputs binds the behavior's input parameters before the search.

func CheckPerformer added in v0.11.0

func CheckPerformer(symbolID string) CheckOption

CheckPerformer names the part or usage whose object performs the behavior.

func CheckProperties added in v0.11.0

func CheckProperties(names ...string) CheckOption

CheckProperties names constraints or requirements evaluated at every stable state.

func CheckWitnessFiles added in v0.11.0

func CheckWitnessFiles() CheckOption

CheckWitnessFiles asks for each witness's file to be carried in the answer.

type CheckSearch added in v0.11.0

type CheckSearch struct {
	States, Moves, MaxDepth int
	BoundsHit               []string
	Horizon                 float64
	HorizonSet              bool
	MassBounded             bool
	Notes, Scope            []string
	Status                  string
}

CheckSearch is the explicit-state search's statistics.

type CheckViolation added in v0.11.0

type CheckViolation struct {
	Kind, Property, Error string
	Depth                 int
	Probability           float64
	Witness               *CheckWitness
	Text                  string
}

CheckViolation is one witnessed violation: Kind is "property", "deadlock" or "failure"; Property names the property for the first, Error the failure.

type CheckWitness added in v0.11.0

type CheckWitness struct {
	Schedule               string
	Draws, Choices, Inputs []string
	FileName, FileContent  string
}

CheckWitness replays one schedule: Schedule is the policy to pass as a run's schedule, Draws/Choices/Inputs what it took, FileName/FileContent its file.

type ChoicePoint added in v0.9.0

type ChoicePoint struct {
	// Kind of choice ("decision branch", "fork order", …).
	Kind string
	// Step of the run the choice was made at.
	Step int
	// Where names the node the choice was made at, as the run traces it
	// ("decision roll").
	Where string
	// Alternatives are what could have been chosen, in declaration order.
	Alternatives []string
	// Taken indexes Alternatives with what was chosen.
	Taken int
}

ChoicePoint is one choice a run made: where it stood, what it could have chosen and what the scheduling policy chose.

type Client

type Client interface {
	// ServerInfo reports the implementation's version and capabilities.
	ServerInfo(ctx context.Context) (*ServerInfo, error)

	// ListEngines lists the analysis engines the service answers with, in name
	// order, as `sysml -engines` does. Requires the engines capability.
	ListEngines(ctx context.Context, opts ...EngineOption) ([]EngineInfo, error)

	// ParseFile parses the model file at path. Diagnostics, including syntax
	// errors, arrive on the returned Model; only an unreadable path or an
	// invalid request fails the call.
	ParseFile(ctx context.Context, path string, opts ...ParseOption) (*Model, error)

	// ParseSource parses inline model source, SysML unless WithLanguage says
	// otherwise. Diagnostics arrive on the returned Model.
	ParseSource(ctx context.Context, content string, opts ...ParseOption) (*Model, error)

	// ParseFiles parses the model files at paths as one model, so a name one
	// file declares resolves in another and an import between them is
	// satisfied. Requires the parse_sources capability.
	ParseFiles(ctx context.Context, paths []string, opts ...ParseOption) (*Model, error)

	// ParseDocuments parses the documents named as one model, for files and
	// inline sources together. Requires the parse_sources capability.
	ParseDocuments(ctx context.Context, documents []Document, opts ...ParseOption) (*Model, error)

	// Diagnostics reports every diagnostic of the parsed model, parser and
	// semantic passes combined — the same list the Model already carries.
	Diagnostics(ctx context.Context, model *Model, opts ...DiagnosticsOption) ([]Diagnostic, error)

	// LookupSymbol looks a symbol up by fully qualified name. An unknown name
	// is a FailureError; an unknown model is CodeNotFound.
	LookupSymbol(ctx context.Context, model *Model, symbolID string) (*Symbol, error)

	// Evaluate evaluates a SysML expression against the parsed model. An
	// expression that does not parse or evaluate is a FailureError carrying
	// the diagnostics; an unknown model is CodeNotFound.
	Evaluate(ctx context.Context, model *Model, expression string, opts ...EvaluateOption) (Value, error)

	// Instantiate instantiates the named part or usage, answering the root
	// instance and everything reachable from it. An unknown symbol or a failed
	// instantiation is a FailureError; an unknown model is CodeNotFound.
	Instantiate(ctx context.Context, model *Model, symbolID string) (*Instantiation, error)

	// ExecuteAction executes the named action with the inputs given, bound by
	// parameter name, and reports the outputs it produced. A Complex input
	// requires the complex_values capability, an Array, Vector or
	// VectorQuantity input the structured_values one, a MeasurementRef input
	// the measurement_refs one, a Function input the function_values one, a Set
	// input the set_values one, a TensorQuantity input the tensor_values one and
	// a Metaobject input the metaobject_values one, checked before anything is
	// sent. WithSchedule selects the scheduling policy, which requires the
	// schedule capability, checked the same way.
	ExecuteAction(ctx context.Context, model *Model, actionSymbolID string, inputs map[string]Value, opts ...ExecuteOption) (*ActionRun, error)

	// ExecuteState runs the named state machine, feeding it the events in
	// order, and reports the states visited and the context left behind.
	// A FailureError from a traced run carries its partial trace and dropped count.
	// WithSchedule selects the scheduling policy, which requires the schedule
	// capability, checked before anything is sent.
	ExecuteState(ctx context.Context, model *Model, stateMachineSymbolID string, events []string, opts ...ExecuteOption) (*StateRun, error)

	// ExploreAction runs the action once per linearization of its choice points,
	// within the budget WithSchedule spells; needs schedule and schedule_explore.
	ExploreAction(ctx context.Context, model *Model, actionSymbolID string, inputs map[string]Value, opts ...ExecuteOption) (*Exploration, error)

	// ExploreState runs the state machine on the events once per linearization
	// of its choice points; an outcome is its final state, visits and values.
	ExploreState(ctx context.Context, model *Model, stateMachineSymbolID string, events []string, opts ...ExecuteOption) (*Exploration, error)

	// ExploreAnalysis runs the case once per linearization of its actions' choice
	// points, under the budget Schedule spells; an outcome is outputs plus verdicts.
	ExploreAnalysis(ctx context.Context, model *Model, symbolID string, opts ...AnalysisOption) (*Exploration, error)

	// VerifyConstraint evaluates the named constraint, optionally Against a
	// part to instantiate and check, WithEngine naming the engine that answers.
	// Requires the verification capability, and engines for a named engine,
	// checked before anything is sent.
	VerifyConstraint(ctx context.Context, model *Model, symbolID string, opts ...VerifyOption) (*Verification, error)

	// VerifyRequirement evaluates the named requirement, optionally Against a
	// part to instantiate and check, WithEngine naming the engine that answers.
	// Requires the verification capability, and engines for a named engine,
	// checked before anything is sent.
	VerifyRequirement(ctx context.Context, model *Model, symbolID string, opts ...VerifyOption) (*Verification, error)

	// VerifySatisfaction evaluates the satisfaction assertions the model
	// states — every one, or those of the symbol named — WithEngine naming the
	// engine that answers; the assertions name their own subjects, so Against
	// is an invalid argument. Requires the verification capability, and engines
	// for a named engine, checked before anything is sent.
	VerifySatisfaction(ctx context.Context, model *Model, symbolID string, opts ...VerifyOption) (*Satisfaction, error)

	// ValidateInstance instantiates the part or usage named and checks every
	// assertion about the object and the objects it holds — asserted constraints
	// and invariants, the requirements carried, and the satisfaction assertions
	// whose subjects are inside it — WithEngine naming the engine that answers;
	// the symbol named is the object validated, so Against is an invalid
	// argument. Requires the verification capability, and engines for a named
	// engine, checked before anything is sent.
	ValidateInstance(ctx context.Context, model *Model, symbolID string, opts ...VerifyOption) (*Validation, error)

	// EvaluateCalc invokes the named calculation with positional arguments, or,
	// given none, evaluates a calc usage from its own members. Requires the
	// verification capability, and the complex_values, structured_values,
	// measurement_refs, function_values, set_values, tensor_values or
	// metaobject_values capability for a Complex, a structured, a
	// MeasurementRef, a Function, a Set, a TensorQuantity or a Metaobject
	// argument, checked before anything is sent.
	EvaluateCalc(ctx context.Context, model *Model, symbolID string, arguments ...Value) (*Calculation, error)

	// Calculate is EvaluateCalc with options: CalcArguments bind the inputs and
	// CalcEngine names the engine that answers. Requires what EvaluateCalc
	// requires, and the engines capability for a named engine, checked before
	// anything is sent.
	Calculate(ctx context.Context, model *Model, symbolID string, opts ...CalcOption) (*Calculation, error)

	// RunAnalysis runs the named analysis case — a definition or a usage — and
	// reports its outputs with the verdict of its objective and of each
	// assertion in its body. Positional arguments bind its inputs in
	// declaration order; Against names its subject and Binding a parameter by
	// name; Schedule selects the scheduling policy and Engine the engine that
	// answers. Requires the verification capability, the complex_values or
	// structured_values capability for a Complex or a structured argument, the
	// schedule capability for a policy and engines for a named engine, checked
	// before anything is sent.
	RunAnalysis(ctx context.Context, model *Model, symbolID string, opts ...AnalysisOption) (*Analysis, error)
	// RunAction and RunMonteCarlo run an action or a Simulation::MonteCarlo case
	// repeatedly and table what the runs observed (runs capability).
	RunAction(ctx context.Context, model *Model, actionID string, count int64, opts ...RunsOption) (*Runs, error)
	RunMonteCarlo(ctx context.Context, model *Model, caseID string, count int64, opts ...RunsOption) (*Runs, error)
	// SelfCheck applies the reflective SysMLValidation constraints to every
	// element of the model (self_check capability).
	SelfCheck(ctx context.Context, model *Model, rulePackages ...string) (*SelfCheck, error)
	// RecordRun runs an analysis case and records the runs into the model
	// (record_run capability).
	RecordRun(ctx context.Context, model *Model, caseID string, opts ...RecordOption) (*Recording, error)

	// Query selects the model's elements the query matches, in declaration
	// order. Requires the query capability.
	Query(ctx context.Context, model *Model, query Query) ([]QueryElement, error)

	// QueryOSLC selects elements with OSLC Query 3.0 parameter text. Requires
	// the oslc_query capability.
	QueryOSLC(ctx context.Context, model *Model, oslc string) ([]QueryElement, error)

	// RunDocumentQuery runs the named document query, binding its entry
	// parameters — to elements, scalars, or objects the service holds for the
	// model since Instantiate (Object) — and answers typed rows. Requires the
	// document_query capability.
	RunDocumentQuery(ctx context.Context, model *Model, queryID string, bindings ...Binding) (*Rows, error)

	// RenderDocument renders the named document to Markdown. Requires the
	// render_document capability.
	RenderDocument(ctx context.Context, model *Model, documentID string) (string, error)

	// RenderView renders a declared view or targeted pseudo-view as diagram
	// data. Ports are minimal by default; WithFullPorts requests all ports.
	// Requires the render_view capability.
	RenderView(ctx context.Context, model *Model, viewName string, opts ...RenderViewOption) (*RenderedView, error)

	// ExportGraphs exports the lowered graph of an action or state machine,
	// and of every behavior it performs, as the canonical graphs:1 JSON an
	// external analysis engine is sent. Requires the export_graphs capability.
	ExportGraphs(ctx context.Context, model *Model, subject string) (*Graphs, error)
	// ImportData sets the feature values data files assign, one edit of the
	// model per file (import_data capability).
	ImportData(ctx context.Context, model *Model, imports []DataImport, opts ...ImportOption) (*ImportResult, error)
	// CompareResults runs the configurations a tool's results sidecar indexes
	// and tables the tool's distributions beside the runs' (compare_results capability).
	CompareResults(ctx context.Context, model *Model, results string, opts ...CompareOption) (*Comparison, error)

	// CheckAction and CheckStateMachine search every schedule of a behavior for a
	// violated property, deadlock, failure or divergent final value (check capability).
	CheckAction(ctx context.Context, model *Model, actionID string, opts ...CheckOption) (*Check, error)
	CheckStateMachine(ctx context.Context, model *Model, stateMachineID string, opts ...CheckOption) (*Check, error)

	// Convert writes the model in another representation, from the source the
	// parse read, so WithFromFormat does not apply and is refused. Requires the
	// convert capability, and a model of one document. ConvertFile converts a
	// file the client never parsed.
	Convert(ctx context.Context, model *Model, to Format, opts ...ConvertOption) (*Conversion, error)

	// ConvertFile writes the model file at path in another representation,
	// inferring its notation from the extension unless WithFromFormat says
	// otherwise. A SysML v1 file (.xmi, .uml, .mdzip, or FormatXMI named) is
	// refused with CodeInvalidArgument: it is migrated by MigrateFile, not
	// converted. Requires the convert capability.
	ConvertFile(ctx context.Context, path string, to Format, opts ...ConvertOption) (*Conversion, error)

	// ConvertSource writes inline content in another representation. Name the
	// notation it is written in with WithFromFormat: there is no file extension
	// to read it from. A v1 format is refused as ConvertFile refuses it.
	// Requires the convert capability.
	ConvertSource(ctx context.Context, content string, to Format, opts ...ConvertOption) (*Conversion, error)

	// MigrateFile migrates the SysML v1 model at path — UML XMI, an Eclipse
	// UML2 .uml file or a .mdzip archive, inferred from the extension unless
	// WithV1Format says — to v2, written in the format to. Migration is not a
	// lossless conversion: every v1 element is mapped, approximated, left
	// unmapped or skipped, and the Migration's Report says which. Requires the
	// migrate capability.
	MigrateFile(ctx context.Context, path string, to Format, opts ...MigrateOption) (*Migration, error)

	// MigrateSource migrates a SysML v1 model carried inline, bytes since a
	// .mdzip archive is binary. Name its form with WithV1Format: there is no
	// file extension to read it from. Requires the migrate capability.
	MigrateSource(ctx context.Context, content []byte, to Format, opts ...MigrateOption) (*Migration, error)

	// ApplyEdits answers the model's source with every edit applied, or refuses
	// them all with an EditError. The edits target the model's first document —
	// its only one when parsed from a file or source — and a rename or cascade
	// delete follows references into every other document of the model, whose
	// rewritten notation the result lists. Requires the apply_edits and
	// edit_documents capabilities.
	ApplyEdits(ctx context.Context, model *Model, edits ...Edit) (*EditResult, error)

	// ApplyDocumentEdits is ApplyEdits with the edits targeting the document
	// named as the parse named it; empty names the first. A name the model has
	// no document under is CodeInvalidArgument. Requires the apply_edits and
	// edit_documents capabilities.
	ApplyDocumentEdits(ctx context.Context, model *Model, document string, edits ...Edit) (*EditResult, error)

	// Close releases what the implementation holds. The Client answers no
	// further calls: each is refused with CodeUnavailable. Closing twice is
	// not an error.
	Close() error
	// contains filtered or unexported methods
}

Client answers SysML v2 questions: parse, look up, evaluate, instantiate. New gives the default in-process implementation and Dial a remote one; both answer identically, which the conformance suite holds them to.

A Client is safe for concurrent use: calls may be made from any number of goroutines, and each answer is the caller's own.

The interface is sealed: implementations come from this package only, so a method can be added without breaking callers.

func Dial

func Dial(address string, opts ...DialOption) (Client, error)

Dial is the remote implementation: the same interface as New, answered by a service someone else runs. The address is explicit — this package never starts a service — and names a sysml-grpc serving the Connect transport ("localhost:50051" or "https://sysml.example.com"); an address without a scheme is dialed as http. Requests cross as Connect protobuf unless WithJSONBody says otherwise. Closing leaves the service running: it was not this package's to stop.

func New

func New(opts ...Option) (Client, error)

New is the in-process implementation: the engine linked into this binary, behind the same interface and semantics as the service — same cache keying, same capability list, same in-band failures — with no port, no child process and no serialization. Runtime budgets and library prewarming are read from the environment, as the service reads them. Close releases the standard library index the client holds.

type Code

type Code uint32

Code is a canonical gRPC status code, the spelling in which the service refuses a call. A Code is itself an error, so a refusal can be tested with errors.Is(err, opensysml.CodeNotFound) whichever implementation answered.

const (
	CodeOK                 Code = 0
	CodeCanceled           Code = 1
	CodeUnknown            Code = 2
	CodeInvalidArgument    Code = 3
	CodeDeadlineExceeded   Code = 4
	CodeNotFound           Code = 5
	CodeAlreadyExists      Code = 6
	CodePermissionDenied   Code = 7
	CodeResourceExhausted  Code = 8
	CodeFailedPrecondition Code = 9
	CodeAborted            Code = 10
	CodeOutOfRange         Code = 11
	CodeUnimplemented      Code = 12
	CodeInternal           Code = 13
	CodeUnavailable        Code = 14
	CodeDataLoss           Code = 15
	CodeUnauthenticated    Code = 16
)

The status codes a call can be refused with, mirroring the canonical gRPC codes. CodeOK never reaches a caller: a call that succeeds returns nil.

func (Code) Error

func (c Code) Error() string

Error makes a Code usable as an errors.Is target.

func (Code) String

func (c Code) String() string

String is the canonical gRPC spelling of the code ("NOT_FOUND").

type CompareOption added in v0.11.0

type CompareOption func(*pb.CompareResultsRequest)

CompareOption shapes a CompareResults call.

func CompareActions added in v0.11.0

func CompareActions(names ...string) CompareOption

CompareActions names the configurations compared, by qualified or simple name.

func CompareClockStep added in v0.11.0

func CompareClockStep(step float64) CompareOption

CompareClockStep replaces every configuration's clock step, in seconds; 0 is continuous.

func CompareDraws added in v0.11.0

func CompareDraws(policy string) CompareOption

CompareDraws replaces every configuration's duration mode: random, min, max or average.

func CompareEngine added in v0.11.0

func CompareEngine(engine string) CompareOption

CompareEngine selects the engine, as ListEngines names them.

func CompareObserve added in v0.11.0

func CompareObserve(stored, feature string) CompareOption

CompareObserve compares the stored observable with the run's feature; an empty feature is the target's feature of the observable's own name.

func CompareRuns added in v0.11.0

func CompareRuns(count int64) CompareOption

CompareRuns makes count runs of every configuration instead of its own numberOfRuns.

func CompareSeed added in v0.11.0

func CompareSeed(seed uint64) CompareOption

CompareSeed seeds the runs; without one, runs that draw at random are refused unless CompareDraws fixes them.

type CompareRow added in v0.11.0

type CompareRow struct {
	Inputs, Outputs map[string]Value
	// Verdicts are the row's objective and assertion verdicts, Evaluations each
	// calc application the row made, as a sweep row reports them.
	Verdicts    []*Verdict
	Evaluations []Evaluation
	Elapsed     time.Duration
	Error       string
	Reason      Reason
}

CompareRow is one run: the run number it bound, what it produced, and the error that stopped it where it failed.

type ComparedDistribution added in v0.11.0

type ComparedDistribution struct {
	Count                               int64
	Min, Mean, P50, P90, Max, Deviation float64
}

ComparedDistribution is a distribution by its statistics; a pooled one knows its count and mean alone.

type Comparison added in v0.11.0

type Comparison struct {
	Source         string
	Configurations []ConfigurationComparison
	Standing       Standing
	Diagnostics    []Diagnostic
}

Comparison is what CompareResults answers: one configuration after another, in the order the sidecar indexes them.

func (*Comparison) Holds added in v0.11.0

func (c *Comparison) Holds() bool

Holds is whether every configuration ran and compared.

type Complex added in v0.5.0

type Complex complex128

Complex is one complex number, never a sequence of two Reals. It is not a Number: a quantity's magnitude is a real magnitude.

func (Complex) String added in v0.5.0

func (z Complex) String() string

String renders the number in rectangular form as SysML writes it: `1.5 - 2.0i`.

type Condition added in v0.4.2

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

Condition is a query filter: one comparison, or several combined. Build one with Equals, In, InstanceOf, Greater, GreaterOrEqual, Less, LessOrEqual, All or Any, and negate it with Not.

func All added in v0.4.2

func All(conditions ...*Condition) *Condition

All matches an element every condition matches. Fewer than two conditions fail the call: the standard combines at least two.

func Any added in v0.4.2

func Any(conditions ...*Condition) *Condition

Any matches an element at least one condition matches. Fewer than two conditions fail the call.

func Equals added in v0.4.2

func Equals(property string, values ...string) *Condition

Equals matches an element whose property is any of the values given. The property names one of the query properties documented in the API reference ("@type", "name", "qualifiedName", …); an unknown one fails the call.

func Greater added in v0.4.2

func Greater(property, value string) *Condition

Greater matches an element whose property is greater than the value.

func GreaterOrEqual added in v0.12.0

func GreaterOrEqual(property, value string) *Condition

GreaterOrEqual matches an element whose property is at least the value.

func In added in v0.12.0

func In(property string, values ...string) *Condition

In matches an element whose property is a member of the values given, the standard's `in` operator. An empty list fails the call.

func InstanceOf added in v0.12.0

func InstanceOf(metaclasses ...string) *Condition

InstanceOf matches an element whose metaclass conforms to any of the named metaclasses ("Usage", "Feature", "Element", …), the standard's `instanceOf` operator on "@type". A name the library declares no metaclass for fails the call.

func Less added in v0.4.2

func Less(property, value string) *Condition

Less matches an element whose property is less than the value.

func LessOrEqual added in v0.12.0

func LessOrEqual(property, value string) *Condition

LessOrEqual matches an element whose property is at most the value.

func (*Condition) Not added in v0.4.2

func (c *Condition) Not() *Condition

Not negates a condition. A comparison negates its verdict; a composite one, which the wire has no negation for, negates each operand and swaps All for Any, which says the same thing.

type ConfigurationComparison added in v0.11.0

type ConfigurationComparison struct {
	ID, Name, Behavior, Target, ResultLocation string
	// Status is holds, undecided (an observable was not compared), fails (a run
	// failed) or unresolved (the configuration could not be run, see Unresolved).
	Status, Unresolved          string
	StoredRuns, StoredSnapshots int64
	Runs, Completed             int64
	Draws                       string
	Seed                        *uint64
	ClockStep                   float64
	Rows                        []CompareRow
	// Instances are the objects the rows' values refer to, by id.
	Instances            []*Instance
	Observables          []ObservableComparison
	Errors, Notes, Lines []string
}

ConfigurationComparison is one configuration's runs beside the tool's results.

type Conversion added in v0.4.2

type Conversion struct {
	// Content is the converted model.
	Content string
	// From and To are the formats used, so a caller that let the source format be
	// inferred learns what it was inferred as.
	From Format
	To   Format
	// Experimental is set when either format is RDF or the API's JSON form, or the
	// source is SysML v1: mappings that may change without a compatibility path.
	Experimental bool
	// ExperimentalNotice says what is experimental about the conversion, empty
	// when it is not.
	ExperimentalNotice string
	// Diagnostics are the syntax errors tolerated, when any were.
	Diagnostics []Diagnostic
	// LibraryReferences are the standard-library elements an API JSON conversion
	// references outside its element array; empty for any other format.
	LibraryReferences []LibraryReference
}

Conversion is a model written in another representation.

type ConvertOption added in v0.4.2

type ConvertOption func(*convertOptions)

ConvertOption configures Convert and ConvertFile.

func WithFromFormat added in v0.4.2

func WithFromFormat(from Format) ConvertOption

WithFromFormat names the notation to read, for a file whose extension does not say and for inline content, which has no extension. Convert refuses it: a parse established what a parsed model was written in.

func WithIDForm added in v0.12.0

func WithIDForm(form IDForm) ConvertOption

WithIDForm spells derived element ids as form when a graph notation is written; declared ids are unchanged. Refused for a notation target.

func WithLibraryStubs added in v0.12.0

func WithLibraryStubs() ConvertOption

WithLibraryStubs restores the pre-0.11.0 ownerless library stubs in API JSON instead of the bare references listed in Conversion.LibraryReferences; requires convert_library_stubs.

func WithTolerateSyntaxErrors added in v0.4.2

func WithTolerateSyntaxErrors() ConvertOption

WithTolerateSyntaxErrors writes notation back out even where the parser could not read all of it, reporting the syntax errors as diagnostics. Notation to notation only: every other direction builds a graph, where unreadable declarations would go missing silently.

type DataImport added in v0.11.0

type DataImport struct {
	Name    string
	Content string
	// Format reads the content as csv, tsv, json or jsonl rather than as the
	// name's extension says.
	Format string
	// Map is the JSON mapping onto elements and features the content is read
	// by; "" for the content's own header.
	Map string
}

DataImport is one data file ImportData sets the feature values of: a CSV, TSV, JSON or JSON Lines text, one row per element, named so its extension names its format unless Format does.

type Delete added in v0.4.2

type Delete struct {
	// Target is the declaration to remove, by qualified name.
	Target string
	// Cascade also removes the declarations that refer to Target.
	Cascade bool
}

Delete removes a declaration and the trivia it owns.

type Diagnostic

type Diagnostic struct {
	// Severity is SeverityError, SeverityWarning or SeverityInfo.
	Severity string
	Message  string
	// Code identifies what was found, stable across message wording ("syntax", a
	// validation code, "choice-point", "guard-unevaluable"); empty when none was assigned.
	Code string
	// Span locates the finding in its source, nil when it has no location.
	Span *Span
}

Diagnostic is one parse or semantic finding.

func (Diagnostic) String added in v0.4.2

func (d Diagnostic) String() string

String renders the finding as a compiler does, locating it when it has a location: "vehicle.sysml:3:5: error: unresolved reference: Engine".

type DiagnosticsOption added in v0.11.0

type DiagnosticsOption func(*pb.DiagnosticsRequest)

DiagnosticsOption selects the lints Diagnostics reports.

func DisableLint added in v0.11.0

func DisableLint(codes ...string) DiagnosticsOption

DisableLint leaves the named lint codes out, as sysml -disable-lint does.

func EnableLint added in v0.11.0

func EnableLint(codes ...string) DiagnosticsOption

EnableLint keeps the named opt-in lint codes in, as sysml -enable-lint does.

type DialOption

type DialOption func(*dialOptions)

DialOption configures Dial.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) DialOption

WithHTTPClient names the HTTP client the connection uses, for callers with their own transport, TLS or timeout policy. The default is http.DefaultClient.

func WithJSONBody

func WithJSONBody() DialOption

WithJSONBody sends requests as Connect JSON instead of protobuf. JSON is a debugging affordance — legible in curl and proxies — and costs an order of magnitude in encoding time on large responses, which is why protobuf is the default.

func WithToken added in v0.12.0

func WithToken(token string) DialOption

WithToken sends the bearer token a sysml-grpc serving an address other machines reach requires, as Authorization: Bearer TOKEN on every call. Without it Dial uses $OPENSYSML_GRPC_TOKEN when that is set.

type Document added in v0.4.2

type Document struct {
	// Path is the file to read. Its extension says which notation it is, and
	// Content, Name and Language are ignored when it is set.
	Path string
	// Content is inline model source, parsed when Path is empty.
	Content string
	// Name is what diagnostics call inline content, and the name it is indexed
	// under. Two documents of one model may not share a name. Empty names it by
	// its position in the parse.
	Name string
	// Language is the notation of inline content, SysML when empty. Requires the
	// inline_language capability when set.
	Language Language
}

Document is one document of a multi-document parse: a file to read, or inline content under a name of the caller's choosing.

func File added in v0.4.2

func File(path string) Document

File is the document read from path.

func Source added in v0.4.2

func Source(name, content string) Document

Source is inline content as a document reported by name.

type DocumentEvent added in v0.9.0

type DocumentEvent struct {
	// Kind is "accept", "send", "transition", "entry", "exit", "do", "choice",
	// "guard" or "terminate"; an action's run adds "step", "wait", "assign",
	// "decide" and "complete".
	Kind string
	// Time is the run's clock when the record was made: a Quantity when the
	// clock carries a unit, a Real otherwise.
	Time Cell
	// Object is the object the record is about; nil for a record of none.
	Object *Object
	// Machine is the state machine the record is about, as DocumentState.Machine names it.
	Machine string
	// State is the state entered, exited or performing, by path, or the action
	// node a wait, assign, decide or accept record is at; From and To are a
	// transition's source and target, or a step's.
	State, From, To string
	// Target is the object a send was addressed to; nil for any other record.
	Target *Object
	// Event is the signal accepted or sent.
	Event string
	// Payload is the accepted signal's arguments as "name = value", by name.
	Payload []string
	// Alternatives are a choice's candidates as offered; Taken is the one drawn.
	Alternatives []string
	Taken        string
	// Text is the record as the trace prints it.
	Text string
	// Token is the action token a step, wait, assign, decide or accept record is
	// about and Step the executor step that made it; 0 for a record of neither.
	Token int64
	Step  int
	// Feature is the feature an assign record wrote and Value what it holds since;
	// Value is nil for any other record.
	Feature string
	Value   Value
}

DocumentEvent is a row an `Events` query answered: one record of a session's trace. It is answered, never bound.

func (DocumentEvent) String added in v0.9.0

func (e DocumentEvent) String() string

String is the event as the trace prints it, prefixed by its time: "1 s: accept Dim".

type DocumentState added in v0.9.0

type DocumentState struct {
	// Object is the object whose state the row reports.
	Object Object
	// Machine is the exhibited state usage's name ("lp"), or the state
	// definition's when the object performs one directly.
	Machine string
	// Name is the active leaf state's name ("dim").
	Name string
	// Path is the leaf's dotted path from the machine's top level ("on.dim").
	Path string
	// State is the leaf's declaration; its ID is empty for an anonymous state.
	State Element
	// Region is the orthogonal region declaring the leaf ("light"); empty for a
	// leaf outside any region.
	Region string
	// Enclosing are the active composite states above the leaf, outermost first.
	Enclosing []string
}

DocumentState is a row a `States` query answered: one active leaf state of the state machine Object exhibits as Machine. It is answered, never bound.

func (DocumentState) String added in v0.9.0

func (s DocumentState) String() string

String is the state in one line: "lamp1.lp in on.dim".

type DocumentVerdict added in v0.9.0

type DocumentVerdict struct {
	// Assertion is the constraint, requirement, satisfy usage or verification
	// case checked; its ID is empty when the assertion is anonymous.
	Assertion Element
	// Kind is "constraint", "requirement", "satisfaction" or "verification".
	Kind string
	// Text is the assertion as written ("assert constraint massKnown").
	Text string
	// Path names the object checked from the element the query was bound to
	// ("Garage::car.wheels[2]").
	Path string
	// Status is "holds", "violated" or "undecided".
	Status string
	// Condition is the condition that evaluated to false, as written; empty otherwise.
	Condition string
	// Reason is why the assertion is violated or undecided; empty when it holds.
	Reason string
	// Verification is the verdict kinds of the verification cases verifying the
	// requirement the row is about; a verification row's own kind.
	Verification []string
}

DocumentVerdict is a row a `Verdicts` query answered: an assertion checked on the object at Path. It is answered, never bound.

func (DocumentVerdict) String added in v0.9.0

func (v DocumentVerdict) String() string

String is the verdict in one line, as the CLI reports it: "assert constraint inflated on Garage::car.wheels[2]: violated".

type Edit added in v0.4.2

type Edit interface {
	// contains filtered or unexported methods
}

Edit is one source-preserving change to a model's notation. A type switch over the supported edit operations is exhaustive.

type EditError added in v0.4.2

type EditError struct {
	FailureError
	// Failure says which refusal this is.
	Failure EditFailure
	// Referring are the FQNs of the namespaces referring to a declaration whose
	// rename or deletion was refused, each suffixed with its document in
	// parentheses when that is not the edited one.
	Referring []string
	// Referrers is Referring with each document as a field of its own, in
	// document then name order.
	Referrers []Referrer
}

EditError is a set of edits the service refused, classified by what it refused. Every refusal is one kind: no edit is silently dropped. It is a FailureError, so errors.Is(err, ErrFailure) matches.

func (*EditError) Unwrap added in v0.4.2

func (e *EditError) Unwrap() error

Unwrap exposes the failure, so errors.As recovers a *FailureError from a refusal.

type EditFailure added in v0.4.2

type EditFailure int32

EditFailure says why edits were refused.

const (
	EditFailureUnspecified       EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_UNSPECIFIED)
	EditFailureNoOperations      EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_NO_OPERATIONS)
	EditFailureUnknownTarget     EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_UNKNOWN_TARGET)
	EditFailureAmbiguousTarget   EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_AMBIGUOUS_TARGET)
	EditFailureNotValued         EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_NOT_VALUED)
	EditFailureInvalidValue      EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_INVALID_VALUE)
	EditFailureInvalidName       EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_INVALID_NAME)
	EditFailureNotNamed          EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_NOT_NAMED)
	EditFailureRenameReferenced  EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_RENAME_REFERENCED)
	EditFailureOverlappingEdits  EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_OVERLAPPING_EDITS)
	EditFailureResultInvalid     EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_RESULT_INVALID)
	EditFailureOwnerUnknown      EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_OWNER_UNKNOWN)
	EditFailureOwnerNotNamespace EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_OWNER_NOT_NAMESPACE)
	EditFailureIllegalKind       EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_ILLEGAL_KIND)
	EditFailureMemberNameTaken   EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_MEMBER_NAME_TAKEN)
	EditFailureDeleteReferenced  EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_DELETE_REFERENCED)
	EditFailureOwnerInsideTarget EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_OWNER_INSIDE_TARGET)
	EditFailureMoveReferenced    EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_MOVE_REFERENCED)
	// EditFailureReferencedElsewhere is a rename, delete or move of a declaration
	// referred to from a document the edit cannot rewrite, such as a library.
	EditFailureReferencedElsewhere EditFailure = EditFailure(pb.EditFailure_EDIT_FAILURE_REFERENCED_ELSEWHERE)
)

The refusals ApplyEdits reports. Every refusal is one of these: an edit is never silently dropped.

func (EditFailure) String added in v0.4.2

func (f EditFailure) String() string

String names the refusal as the wire enum spells it.

type EditResult added in v0.4.2

type EditResult struct {
	// Documents is the edited notation of every document the edits rewrote: the
	// edited document first when it is among them, then the others in name order.
	// A single-document model's one document is always listed; a document of
	// several the edits left as parsed is not.
	Documents []EditedDocument
	// Applied says what each edit changed, grouped by document in the order
	// Documents lists them and in request order within a document.
	Applied []AppliedEdit
	// Diagnostics the edited source was found to have, when any.
	Diagnostics []Diagnostic
}

EditResult is a model's source with every edit applied.

type EditedDocument added in v0.9.0

type EditedDocument struct {
	// Name is the document's name as the parse gave it: a File's path, a
	// Document's Name, or the position of an inline document named neither.
	Name string
	// Content is the edited notation, byte-identical to the source outside the
	// edited spans.
	Content string
}

EditedDocument is the edited notation of one document of a model.

type Element added in v0.4.2

type Element struct {
	// ID is the element's qualified name, the identity a binding names it by.
	ID string
	// Type is its metamodel type name ("PartUsage", …); answered, never bound.
	Type string
}

Element is a model element a document query selected or was bound to, named by qualified name.

func (Element) String added in v0.4.2

func (e Element) String() string

String is the element as a binding names it, its qualified name.

type EngineInfo added in v0.8.0

type EngineInfo struct {
	// Name is the engine's name, what an engine option spells.
	Name string
	// Authority is the strongest strength the engine's answers may carry.
	Authority string
	// Answers are the question kinds the engine answers.
	Answers []string
	// Bounds are the names of the bounds the engine reports on its answers.
	Bounds []string
	// Process is the external process the engine runs, empty for none.
	Process string
	// ProcessFound is where that process was found, empty when it was not.
	ProcessFound string
	// Ready is whether the engine can answer now.
	Ready bool
	// Unavailable says why the engine cannot answer, empty when Ready.
	Unavailable string
}

EngineInfo is one analysis engine the service answers with, as ListEngines and `sysml -engines` report it.

type EngineOption added in v0.11.0

type EngineOption func(*pb.ListEnginesRequest)

EngineOption configures ListEngines.

func Probe added in v0.11.0

func Probe() EngineOption

Probe starts each external engine the service serves and checks its handshake, as sysml -probe does, so Ready reports what the process said.

type EnumLiteral

type EnumLiteral struct {
	// LiteralID is the FQN of the literal's declaration ("D::Color::red").
	LiteralID string
	// EnumerationID is the FQN of the enumeration declaring it ("D::Color").
	EnumerationID string
	// Name is the literal as a reader writes it ("Color::red").
	Name string
	// Value is the scalar the literal equals — Int(3) for `high = 3` of an
	// enumeration specializing Integer — or nil for a literal that is only its
	// identity. It describes the literal and is no part of its identity.
	Value Value
}

EnumLiteral is one literal of an enumeration definition. A literal is its own identity: two values are the same literal exactly when LiteralID is.

func (EnumLiteral) String added in v0.4.2

func (e EnumLiteral) String() string

String is the literal as a reader writes it, the Name the service reported.

type EvaluateOption

type EvaluateOption func(*evaluateOptions)

EvaluateOption configures Evaluate.

func WithContextSymbol

func WithContextSymbol(symbolID string) EvaluateOption

WithContextSymbol names the symbol whose scope the expression's names are resolved in.

func WithSubject

func WithSubject(symbolID string) EvaluateOption

WithSubject names a symbol to instantiate and evaluate against, so a feature reads that object's value rather than the declared default. Requires the evaluate_subject capability.

type Evaluation added in v0.7.0

type Evaluation struct {
	// FunctionID is the FQN of the calc applied.
	FunctionID string
	// Arguments it was applied to, in parameter order; an alternative is an
	// InstanceID that Analysis.Instance resolves.
	Arguments []Value
	// Result is what it computed, nil when Error says why it computed nothing.
	Result Value
	// Error is set when the application failed rather than computed a value.
	Error string
	// Selected marks the evaluation whose argument selectOne picked and the case
	// returned: the alternative a trade study selected.
	Selected bool
	// Tied marks an evaluation computing what the selected one did without
	// being it: an alternative scoring the same as the one selected.
	Tied bool
}

Evaluation is one application of a calc the case declares, made while it ran. For a trade study it is the evaluationFunction scoring one alternative.

type ExecuteOption added in v0.7.0

type ExecuteOption func(*executeOptions)

ExecuteOption configures ExecuteAction and ExecuteState.

func PerformedBy added in v0.9.0

func PerformedBy(path string) ExecuteOption

PerformedBy names the object performing the behavior, as sysml -action "<action> <object>" does: a declaration the run creates an object of, or a path into one ("Mission::mission.vehicle").

func WithAdvance added in v0.11.0

func WithAdvance(seconds float64) ExecuteOption

WithAdvance runs the behavior for that many simulated seconds, as sysml -advance does, instead of to completion; a run still waiting then is a *FailureError that still reports FinalTime.

func WithClockStep added in v0.11.0

func WithClockStep(seconds float64) ExecuteOption

WithClockStep ticks the run's clock in steps of that many seconds, as sysml -clock-step does; 0 is a continuous clock.

func WithDraws added in v0.11.0

func WithDraws(policy string) ExecuteOption

WithDraws chooses how the model's draws resolve, as sysml -draws spells it: "random", "min", "max" or "average".

func WithEvents added in v0.12.0

func WithEvents(events ...string) ExecuteOption

WithEvents posts the named signals to the object an action is performed on (PerformedBy), in order, each once every token of the run waits, as the REPL's %send does; the accept waiting for it takes it on the next step.

func WithSchedule added in v0.7.0

func WithSchedule(policy string) ExecuteOption

WithSchedule names the policy a run resolves its choice points under, as sysml -schedule spells it; "explore[...]" belongs to ExploreAction and ExploreState.

func WithSeed added in v0.11.0

func WithSeed(seed uint64) ExecuteOption

WithSeed seeds the model's own draws, as sysml -seed does, so RandomFunctions answer the same values each run.

func WithTrace added in v0.10.0

func WithTrace() ExecuteOption

WithTrace asks ExecuteAction or ExecuteState to return the run's execution trace; the service must have CapabilityActionTrace or CapabilityStateTrace.

type Exploration added in v0.7.0

type Exploration struct {
	Outcomes []Outcome
	// Complete is true when every linearization within the budget was run, so
	// Outcomes is the whole set.
	Complete bool
	// Runs is how many runs the exploration made.
	Runs int
	// BudgetsHit names the budgets that ended the search, "runs" before
	// "depth"; empty when Complete.
	BudgetsHit []string
	// RunsBudget and DepthBudget are the budget the search ran under: runs it
	// may make, and choice points one run may resolve.
	RunsBudget  int
	DepthBudget int
	// FailedLinearizations counts runs whose outcomes carry runtime errors.
	FailedLinearizations int
	// ProbabilitiesLowerBound reports the outcomes' probabilities are lower
	// bounds: a budget kept some linearizations unexplored.
	ProbabilitiesLowerBound bool
}

Exploration is what exploring a behavior found: every distinct outcome, in the service's canonical order, and how the search ended.

func (*Exploration) Status added in v0.7.0

func (e *Exploration) Status() string

Status renders how the exploration ended as the sysml command does: "complete (N runs)", or the budget hit after how many runs.

type FailureError

type FailureError struct {
	// Op is the Client method that was answered ("Evaluate", "LookupSymbol").
	Op string
	// Message is the response's error field, verbatim.
	Message string
	// Diagnostics the response carried alongside the failure, if any.
	Diagnostics []Diagnostic
	// Trace is the partial ExecuteAction or ExecuteState trace when a traced run failed.
	Trace []DocumentEvent
	// TraceDropped is the number of oldest trace records discarded.
	TraceDropped int
	// FinalTime is the simulation clock an ExecuteAction or ExecuteState run
	// stopped at, in seconds, when it failed under WithAdvance.
	FinalTime float64
}

FailureError is a failure the service reported in a successful answer — an unparsable expression, an unknown symbol, a failed instantiation. It is deliberately distinct from StatusError: on the wire the call succeeds with status OK and the response's error field set.

func (*FailureError) Error

func (e *FailureError) Error() string

Error renders the failure the service reported.

func (*FailureError) Is

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

Is matches ErrFailure, so errors.Is(err, opensysml.ErrFailure) is true for every in-band failure.

type FeatureValue

type FeatureValue struct {
	FeatureName string
	// Value for a single-valued feature, nil when Values or Error applies.
	Value Value
	// Values for a multi-valued feature.
	Values []Value
	// Materialized reports whether the value was computed rather than read.
	Materialized bool
	// Error is set when evaluating the feature failed; Value is then nil.
	Error string
}

FeatureValue is what an object holds for one feature of its type.

type Format added in v0.4.2

type Format string

Format is a representation a model is written in or read from.

const (
	FormatSysML Format = "sysml"
	FormatTTL   Format = "ttl"
	// FormatKerML and FormatText are aliases of FormatSysML: notation is one
	// format, read and written by the same parser and printer.
	FormatKerML Format = "kerml"
	FormatText  Format = "text"
	// FormatTurtle and FormatRDF are aliases of FormatTTL, the one RDF
	// serialization written.
	FormatTurtle  Format = "turtle"
	FormatRDF     Format = "rdf"
	FormatAPIJSON Format = "api-json"
	// FormatJSON is an alias of FormatAPIJSON, the OMG API's JSON element
	// form of the same graph FormatTTL writes.
	FormatJSON Format = "json"
	// FormatXMI is SysML v1 as UML XMI 2.5.1 with the SysML profile applied,
	// an Eclipse UML2 .uml file or a .mdzip archive: an input to MigrateFile and
	// MigrateSource only, which answer every v1 form by this name. Asking to
	// write it, or to convert from it, is refused.
	FormatXMI Format = "xmi"
	// FormatUML and FormatMDZip name the Eclipse UML2 and the Cameo/MagicDraw
	// archive forms of FormatXMI, for a v1 file whose extension does not say.
	FormatUML   Format = "uml"
	FormatMDZip Format = "mdzip"
)

The formats conversion and migration accept. There are three canonical ones that are written, FormatSysML, FormatTTL and FormatAPIJSON, and a Conversion or a Migration answers by those names whichever alias was asked for. RDF and the API's JSON element form, in any spelling, are one experimental mapping, which a Conversion reports; so is migration from FormatXMI, which is only ever read, and only by MigrateFile and MigrateSource.

type Function added in v0.7.0

type Function struct {
	// CalcID is the FQN of the calc declaration ("M::Sq").
	CalcID string
	// Self is the object the calc computes over, an id of the answer that
	// reported it; 0 for a calc bound to no object. As any InstanceID it lives
	// only within that answer: sent as an argument, a non-zero Self is refused.
	Self InstanceID
}

Function is a calc held as a value: a calc definition, a calc usage or an `in calc` parameter read where a value is expected. It names the calc and, for one read off an object, that object; sent as an argument it is invoked through the calc-typed parameter it binds. Identity is the calc together with Self.

func (Function) String added in v0.7.0

func (f Function) String() string

String names the calc the function is a value of.

type Graphs added in v0.10.0

type Graphs struct {
	// Content is the form as canonical JSON, ending in one newline.
	Content string
	// Version is the version of the form, the `version` field of the JSON.
	Version int
	// Subject is the qualified name of the behavior as resolved.
	Subject string
}

Graphs is the lowered graph of an action or state machine and of every behavior it performs, in the canonical `graphs:<Version>` JSON form an external analysis engine is sent.

type IDForm added in v0.12.0

type IDForm string

IDForm is how a graph notation (Turtle, API JSON) spells the ids of elements that declared none.

const (
	// IDFormQualified derives each id from the element's qualified name; the default.
	IDFormQualified IDForm = "qualified"
	// IDFormUUID writes name-based uuids under each root package, the library convention.
	IDFormUUID IDForm = "uuid"
)

type ImportOption added in v0.11.0

type ImportOption func(*importOptions)

ImportOption shapes an ImportData call.

func ImportAcceptDocuments added in v0.11.0

func ImportAcceptDocuments() ImportOption

ImportAcceptDocuments accepts every edited document of a model of several.

func ImportAs added in v0.12.0

func ImportAs(form string) ImportOption

ImportAs names what each row is made into, as `sysml -import-as` does: ImportAsValues. Another name is refused by the service as INVALID_ARGUMENT.

func ImportDryRun added in v0.11.0

func ImportDryRun() ImportOption

ImportDryRun reports the values the imports would set, changing nothing.

type ImportResult added in v0.11.0

type ImportResult struct {
	Files []ImportedFile
	// Content is the edited content of a one-document model; Documents every
	// edited document. Both are empty on a dry run.
	Content   string
	Documents []EditedDocument
	// ModelHash is the imported model's, parsed and cached; "" on a dry run.
	ModelHash   string
	Diagnostics []Diagnostic
}

ImportResult is what ImportData answers: what each file set, and the model it made.

type ImportedFile added in v0.11.0

type ImportedFile struct {
	Name             string
	Values, Elements int64
	Assignments      []ImportedValue
}

ImportedFile is what one data file set.

type ImportedValue added in v0.11.0

type ImportedValue struct {
	Element, Feature, Value, Redefines, Where, Description string
}

ImportedValue is one assignment: the feature of the element set to the value, redefining the inherited feature Redefines when the element did not declare it, and where in the data it came from.

type Infinity added in v0.4.2

type Infinity struct{}

Infinity is an unbounded multiplicity. It is answered, never bound.

func (Infinity) String added in v0.4.2

func (Infinity) String() string

String reports an unbounded multiplicity as the notation writes it.

type Instance

type Instance struct {
	// ID names the instance within its Instantiation; an InstanceID value
	// elsewhere in the answer refers to it.
	ID int64
	// TypeSymbolID is the FQN of the def/usage this is an instance of.
	TypeSymbolID string
	// FeatureValues are what the object holds for each feature of its type,
	// by feature name.
	FeatureValues map[string]FeatureValue
}

Instance is a runtime instance of a part or usage.

type InstanceID

type InstanceID int64

InstanceID refers to an Instance by the id an Instantiation assigned it. Ids are per call: they name instances within one answer, nothing beyond it.

type Instantiation

type Instantiation struct {
	// Root is the instance of the symbol that was instantiated.
	Root *Instance
	// Instances is every instance reachable from Root, including Root itself,
	// in the order the service reported them.
	Instances []*Instance
	// Diagnostics the answer carried, if any.
	Diagnostics []Diagnostic
}

Instantiation is the result of instantiating a symbol: the root instance and every instance reachable from it, so an InstanceID resolves without another call.

func (*Instantiation) Instance added in v0.4.2

func (i *Instantiation) Instance(id InstanceID) *Instance

Instance resolves an InstanceID a value referred to, nil when this instantiation holds no such instance.

type Int

type Int int64

Int is an integer value within int64.

type Language

type Language string

Language selects the notation of inline content.

const (
	LanguageSysML Language = "sysml"
	LanguageKerML Language = "kerml"
)

The languages ParseSource accepts.

type LibraryReference added in v0.12.0

type LibraryReference struct {
	ID            string
	QualifiedName string
	// Type is the element's metaclass, as API JSON's @type spells it.
	Type string
}

LibraryReference is a standard-library element an API JSON conversion references outside its element array, in place of a library stub.

type MeasurementRef added in v0.6.0

type MeasurementRef struct {
	// Unit as written ("km") or as an operation composed it ("m/s"); empty
	// for one never written down, described by Term alone.
	Unit string
	// Term is what the unit reduces to. Required wherever Unit names a unit.
	Term *UnitTerm
	// UnitID is the FQN of the one unit declaration the reference names
	// ("SI::kilometre"); empty for a unit an operation composed, which names none.
	UnitID string
}

MeasurementRef is a measurement unit held as a value by itself, with no magnitude: `SI::m`, `km`, or `m / s` as an operation composed it. It is what a MeasurementUnit-typed attribute or a quantity's mRef evaluates to, and what ConvertQuantity takes as its target.

func (MeasurementRef) String added in v0.6.0

func (r MeasurementRef) String() string

String renders the reference as SysML writes the unit: `km`, `m/s`; one never written down renders its reduction.

type Member added in v0.9.0

type Member struct {
	// ID is the member's fully qualified name.
	ID   string
	Name string
	// Kind of the member ("PartUsage", "EnumerationUsage", …).
	Kind string
}

Member is one named member a declaration's scope holds.

type MetadataValue added in v0.9.2

type MetadataValue struct {
	// Feature is the metadata feature reference.
	Feature string
	// Value is the feature value expression, written as notation.
	Value string
}

MetadataValue is one feature binding in a metadata usage.

type Metaobject added in v0.8.0

type Metaobject struct {
	// ElementID is the FQN of the element reflected on ("Vehicle::seatBelt").
	ElementID string
	// MetaclassID is the FQN of the element's own reflective metaclass
	// ("SysML::Systems::PartUsage"), not the type it was cast to. The service
	// always reports it; a caller may leave it empty to have the model's used.
	MetaclassID string
}

Metaobject is an element of the model held as an instance of its reflective metaclass: what `x meta KerML::Feature`, or the last element of `x.metadata`, evaluates to. Identity is the element: two metaobjects are the same exactly when ElementID is. Its features are read in the model, not carried.

func (Metaobject) String added in v0.8.0

func (m Metaobject) String() string

String is the metaobject as the REPL shows it: the element and its metaclass.

type MigrateOption added in v0.10.0

type MigrateOption func(*migrateOptions)

MigrateOption configures MigrateFile and MigrateSource.

func WithImageBaseURL added in v0.10.0

func WithImageBaseURL(url string) MigrateOption

WithImageBaseURL resolves a server-relative image reference in a v1 comment (<img src="/projects/…">) against an absolute http(s) URL.

func WithLayout added in v0.10.0

func WithLayout(content string) MigrateOption

WithLayout lays the migrated views out from an MTIP export carried inline.

func WithLayoutFile added in v0.10.0

func WithLayoutFile(path string) MigrateOption

WithLayoutFile lays the migrated views out from an MTIP export of the model's diagrams (Model_mtip.xml) at path, which the service reads.

func WithMigrationReport added in v0.10.0

func WithMigrationReport() MigrateOption

WithMigrationReport asks for every element's verdict in the Migration's Report, with the report's text as `sysml -migration-report` writes it. The summary and the counts come back whether or not it is given.

func WithMigrationResults added in v0.10.0

func WithMigrationResults() MigrateOption

WithMigrationResults asks for the result snapshots the v1 tool stored with the model, indexed as `sysml -migration-results` writes them, in the Migration's Results.

func WithStrict added in v0.10.0

func WithStrict() MigrateOption

WithStrict writes only notation a pinned SysML v2 production admits: a construct whose only v2 form is an OpenSysML extension (a deferred event, a choice, junction or history pseudostate) is reported unmapped instead of written.

func WithV1Format added in v0.10.0

func WithV1Format(from Format) MigrateOption

WithV1Format names the v1 form to read — FormatXMI, FormatUML or FormatMDZip — for a file whose extension does not say and for inline content, which has no extension.

type Migration added in v0.10.0

type Migration struct {
	// Content is the migrated model.
	Content string
	// From is FormatXMI whichever v1 form was read; To is the format written,
	// canonical whichever alias was asked for.
	From Format
	To   Format
	// ExperimentalNotice says what is experimental about the migration — every
	// migration is — in the wording every surface reports it in.
	ExperimentalNotice string
	// Report accounts for the migration: its Summary and counts always, its
	// Entries and Text when WithMigrationReport asked for them.
	Report *MigrationReport
	// Results is the JSON index of the result snapshots the v1 tool stored,
	// what `sysml -compare-results` reads, when WithMigrationResults asked for
	// it; empty otherwise.
	Results string
	// Files are the image files the migrated model refers to by relative path,
	// to be written beside it; empty when it refers to none.
	Files map[string][]byte
}

Migration is a SysML v1 model written as a v2 one, with the account of what the migration did with every v1 element. Migration is not a lossless conversion: the Report says which elements were mapped, approximated, left unmapped or skipped.

type MigrationEntry added in v0.10.0

type MigrationEntry struct {
	// ID is the element's xmi:id, the handle a v1 tool addresses it by.
	ID string
	// Kind is the element as modeled — its stereotype when one classifies it,
	// else its UML metaclass — and Name its qualified name in v1.
	Kind string
	Name string
	// Target is the v2 declaration written for it, a qualified name with its
	// keyword, or empty when nothing was.
	Target string
	// Verdict is "mapped", "approximated", "unmapped" or "skipped", and Note
	// says why for every verdict but mapped.
	Verdict string
	Note    string
}

MigrationEntry is the verdict on one SysML v1 element.

type MigrationReport added in v0.10.0

type MigrationReport struct {
	// Source names the v1 document migrated; Exporter the tool that wrote it,
	// when the document says.
	Source   string
	Exporter string
	// Summary is the one-line account `sysml -migrate` prints.
	Summary string
	// The verdict counts: mapped to a v2 counterpart that states the same
	// thing, approximated by a v2 form that loses or restates part of what v1
	// said, left unmapped and recorded as a comment where the element stood,
	// or skipped as a profile, library or notation-only element nothing in the
	// model refers to.
	Mapped       int
	Approximated int
	Unmapped     int
	Skipped      int
	// Entries are every element's verdict, when WithMigrationReport asked for
	// them; Text is then the report as `sysml -migration-report` writes it.
	Entries []MigrationEntry
	Text    string
}

MigrationReport accounts for every element of a SysML v1 model.

type Model

type Model struct {
	// Hash is the content-addressed cache key the service assigned the parse.
	Hash string
	// Root is the root namespace of the model's first document.
	Root *Symbol
	// Roots is the root namespace of each document, in the order the parse named
	// them; one entry for a model parsed from a single file or source.
	Roots []*Symbol
	// Diagnostics from parsing and semantic analysis. A syntax error is a
	// diagnostic here, not a failed call.
	Diagnostics []Diagnostic
	// Affected names the documents whose results may differ from the base
	// model's, when ParseDocuments was given WithBaseModel; nil otherwise.
	Affected []string
}

Model is a parsed model, the handle the other calls take. It is data the caller owns: mutating it changes nothing in the engine or the service.

func (*Model) Errors added in v0.4.2

func (m *Model) Errors() []Diagnostic

Errors are the model's diagnostics of severity "error", the ones that make a model unusable rather than merely questionable.

func (*Model) OK added in v0.4.2

func (m *Model) OK() bool

OK reports a model that parsed and analyzed without an error diagnostic. Warnings do not make it false; no model at all does.

type Move added in v0.8.0

type Move struct {
	// Target is the declaration to move, by qualified name.
	Target string
	// Owner is the namespace to receive it; empty is the document root.
	Owner string
}

Move re-parents a declaration into another namespace of the same document, carrying its body and owned trivia and respelling the references it breaks.

type Multiplicity

type Multiplicity struct {
	Lower string // "0", "1", … or "*"
	Upper string // "1", "*", …
}

Multiplicity is a declared multiplicity range. A bound the service cannot evaluate statically is empty.

type Null

type Null string

Null is the absence of a value. Its text is the service's reason when it has one ("unsupported: variant selection"), and empty for a plain null.

func (Null) String added in v0.4.2

func (n Null) String() string

String reports the absence of a value, with the service's reason when it gave one.

type Number

type Number interface {
	Value
	// contains filtered or unexported methods
}

Number is a Value that is a numeric magnitude: Int, BigInt, Rational or Real. Integers, rationals and reals stay apart end to end, so an exact number compares exactly.

func NewInteger added in v0.10.0

func NewInteger(n *big.Int) Number

NewInteger is n as the integer value it is: an Int within int64, otherwise a BigInt holding a copy of n.

type Object added in v0.9.0

type Object struct {
	// ID is the object's id, as Instantiate answered it.
	ID int64
	// Path is the object by the label a session reaches it under: the qualified
	// name it was instantiated as ("Garage::car"), its id ("#2"), or a path
	// through feature values of either ("Garage::car.wheels[2]", "#2.wheels[2]";
	// indexes count from 1).
	Path string
	// Element is the usage the object is held under, its definition or usage;
	// answered, ignored when bound.
	Element Element
}

Object is an object the service holds for the model, created by Instantiate. Bound, it names the object by Path when set and by ID otherwise (both must then name one object); answered, it carries ID, Path and Element.

func ObjectByID added in v0.9.0

func ObjectByID(id int64) Object

ObjectByID names a held object by the id Instantiate answered.

func ObjectByPath added in v0.9.0

func ObjectByPath(path string) Object

ObjectByPath names a held object by name, id or path ("car", "#2", "car.wheels[2]").

func (Object) String added in v0.9.0

func (o Object) String() string

String is the object as a session names it: its path when it has one, else its id ("#2").

type ObservableComparison added in v0.11.0

type ObservableComparison struct {
	Stored, Feature, Unit string
	Tool                  *ComparedDistribution
	Pooled, Unstored      bool
	Run                   *ComparedDistribution
	Produced              int64
	Compared              bool
	Difference            *StatisticDifference
	Declared              *CaseStatistics
	Notes                 []string
}

ObservableComparison is one observable: the tool's distribution beside the runs', or the notes on why they are not compared.

type Option

type Option func(*options)

Option configures New.

func WithCacheSize

func WithCacheSize(size int) Option

WithCacheSize bounds how many parsed models the client keeps, evicting the least recently used beyond it. The default is 100; New refuses a size that is not positive.

type Outcome added in v0.7.0

type Outcome struct {
	// Outputs are an action's outputs, a state machine's final context, or a
	// case's outputs and verdicts ("objective <name>", "assertion <name>", "verdict <case>").
	Outputs map[string]Value
	// FinalState is the state a machine rests in and Visited the states it
	// entered, in order; both empty for an action or a case.
	FinalState string
	Visited    []string
	// Error is what the runs reaching this outcome failed with; empty when they completed.
	Error string
	// Linearizations is how many runs within the budget reached this outcome.
	Linearizations int
	// Probability is the exact model-draw probability, or zero when inexact or absent.
	Probability float64
	// ProbabilityRange bounds the model-draw probability over schedulers.
	ProbabilityRange *ProbabilityRange
	// Witness is one run's choices in run order, one per choice point it
	// resolved, each spelling the alternatives and the one taken.
	Witness []string
	// Diagnostics are what the witness run reported about itself.
	Diagnostics []Diagnostic
}

Outcome is one distinct outcome an exploration reached, with how many linearizations reached it and the choices of one run that did.

func (*Outcome) Failed added in v0.7.0

func (o *Outcome) Failed() bool

Failed reports an outcome of runs that failed rather than completed.

type ParseOption

type ParseOption func(*parseOptions)

ParseOption configures the parse calls.

func WithBaseModel added in v0.12.0

func WithBaseModel(base *Model) ParseOption

WithBaseModel relates ParseDocuments to a previous model of the same documents, so Model.Affected names the documents whose results may differ; requires parse_sources_affected.

func WithLanguage

func WithLanguage(language Language) ParseOption

WithLanguage names the notation of inline content: LanguageSysML (the default) or LanguageKerML. File parsing infers the notation from the file extension instead.

func WithStrictConformance

func WithStrictConformance() ParseOption

WithStrictConformance asks for the source to be judged as conforming SysML v2: notation no pinned production admits is an error rather than a warning. Requires the strict_conformance capability.

type Performance added in v0.9.0

type Performance struct {
	// Outputs are the action's out parameters, by name.
	Outputs map[string]Value
	// Choices the run made, in order.
	Choices []ChoicePoint
	// Branches are the decisions of the action's own flow the run left, in order.
	Branches []Branch
	// Diagnostics the run raised.
	Diagnostics []Diagnostic
}

Performance is what performing an action did.

func (*Performance) TurnedAway added in v0.9.0

func (p *Performance) TurnedAway() bool

TurnedAway reports whether the run left the action's opening decision by its else branch: the action looked at its inputs or its performer and declined.

type ProbabilityRange added in v0.10.0

type ProbabilityRange struct{ Min, Max float64 }

ProbabilityRange bounds a model-draw probability over schedulers.

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 struct {
	// Magnitude keeps Int and Real apart, as the rest of Value does.
	Magnitude Number
	// Unit as written ("km/h"), or as an operation composed it ("m/s"); empty
	// for a unit never written down, described by Term alone.
	Unit string
	// Term is what the unit reduces to, which decides commensurability.
	Term *UnitTerm
}

Quantity is a magnitude and the measurement unit it is expressed in, exactly as written: 5.4 km/h arrives as 5.4 km/h, not converted to base units.

func (Quantity) String added in v0.4.2

func (q Quantity) String() string

String renders the quantity as it was written: magnitude then unit.

type Query added in v0.4.2

type Query struct {
	// Scope names the elements considered by qualified name, each together with
	// everything nested inside it. Empty considers the whole model.
	Scope []string
	// Select names the properties to report. Empty reports all of them.
	Select []string
	// Where is the filter every considered element must satisfy, nil for none.
	Where *Condition
	// OrderBy names the properties the selected elements are sorted by, in
	// order of precedence, each ascending; elements equal under every one keep
	// declaration order. Empty keeps declaration order throughout.
	OrderBy []string
}

Query selects elements of a model, as the SysML v2 API & Services Query resource does: the elements considered, the properties reported for each, and the filter every one must satisfy.

type QueryElement added in v0.4.2

type QueryElement struct {
	// ID is the element's qualified name.
	ID string
	// Type is its metamodel type name ("PartUsage", "PartDefinition", …).
	Type string
	// Properties carries what Select asked for, omitting a property the element
	// does not have.
	Properties map[string]string
}

QueryElement is one element a query selected.

type Rational added in v0.10.0

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

Rational is an exact rational value no Real holds exactly: KerML Rationals are exact, so 0.1 is one tenth and 1 / 3 one third. A Rational a binary64 holds exactly, such as 0.5, crosses the wire as that Real.

func NewRational added in v0.10.0

func NewRational(r *big.Rat) Rational

NewRational is a Rational holding a copy of r.

func (Rational) Float64 added in v0.10.0

func (q Rational) Float64() float64

Float64 is the binary64 nearest the rational.

func (Rational) Rat added in v0.10.0

func (q Rational) Rat() *big.Rat

Rat returns a copy of the rational.

func (Rational) String added in v0.10.0

func (q Rational) String() string

String spells the rational exactly, as the service prints it: a terminating decimal as `0.1`, any other as `1/3`.

type Real

type Real float64

Real is a real value.

type Reason added in v0.4.2

type Reason int32

Reason says what kind of failure an undecided verdict or a failed calculation reports, so a caller acts on the kind rather than on the message text.

const (
	// ReasonUnspecified is no failure, or one the service did not classify.
	ReasonUnspecified Reason = Reason(pb.FailureReason_FAILURE_REASON_UNSPECIFIED)
	// ReasonEvaluation is a condition or calculation that could not be evaluated.
	ReasonEvaluation Reason = Reason(pb.FailureReason_FAILURE_REASON_EVALUATION)
	// ReasonWrongKind is a symbol that declares something else than was asked about.
	ReasonWrongKind Reason = Reason(pb.FailureReason_FAILURE_REASON_WRONG_KIND)
	// ReasonAmbiguousSubject is several objects carrying the element: name one.
	ReasonAmbiguousSubject Reason = Reason(pb.FailureReason_FAILURE_REASON_AMBIGUOUS_SUBJECT)
	// ReasonUndecided is an engine that was asked but decided nothing.
	ReasonUndecided Reason = Reason(pb.FailureReason_FAILURE_REASON_UNDECIDED)
)

The failure kinds a verification or calculation reports.

func (Reason) String added in v0.4.2

func (r Reason) String() string

String names the reason as the wire enum spells it.

type RecordOption added in v0.11.0

type RecordOption func(*recordOptions)

RecordOption configures RecordRun.

func RecordArgument added in v0.11.0

func RecordArgument(name string, value Value) RecordOption

RecordArgument binds one of the case's in parameters by name.

func RecordArguments added in v0.11.0

func RecordArguments(values ...Value) RecordOption

RecordArguments binds the case's in parameters positionally.

func RecordEngine added in v0.11.0

func RecordEngine(name string) RecordOption

RecordEngine selects the analysis engine asked; empty is auto.

func RecordInto added in v0.11.0

func RecordInto(pkg string) RecordOption

RecordInto names the package the records go into; empty is a Records package beside the package enclosing the case's own.

func RecordRange added in v0.11.0

func RecordRange(parameter string, start, end, step Value) RecordOption

RecordRange runs the case once per value of a parameter stepped from start to end, as a sweep does, and records each completed row; several ranges make their product.

func RecordSample added in v0.11.0

func RecordSample(count int64, seed uint64) RecordOption

RecordSample runs the Simulation::MonteCarlo case count times from seed and records each completed run and the sample's conclusion.

func RecordSubject added in v0.11.0

func RecordSubject(symbolID string) RecordOption

RecordSubject names the part/usage to instantiate as the case's subject.

type RecordedDocument added in v0.11.0

type RecordedDocument struct {
	Name, Content string
}

RecordedDocument is one document the records were written into.

type Recording added in v0.11.0

type Recording struct {
	// Run, Sweep or Sample is the runs' own result, by how the case ran.
	Run    *Analysis
	Sweep  []RunRow
	Sample *Runs
	// Package, Definition and Records name what the model gained; Source is
	// the declarations generated.
	Package, Definition string
	Records             []string
	Source              string
	// Content is the recorded notation of a single-document model the records
	// merged into; Documents always carries the document they went into, or
	// the records as a document of their own.
	Content   string
	Documents []RecordedDocument
	// Skipped counts the rows or runs that failed and were not recorded;
	// Reasons says why runs were not recorded.
	Skipped int64
	Reasons []string
	// ModelHash names the recorded model, cached for the next request.
	ModelHash   string
	Diagnostics []Diagnostic
}

Recording is what RecordRun answers: the runs' own report, what the model gained and the notation the records were written into.

type Referrer added in v0.9.0

type Referrer struct {
	// Name is the referring declaration, as the notation names it.
	Name string
	// Document is the document declaring it, named as in EditedDocument.
	Document string
}

Referrer is one declaration referring to the target of a refused rename, delete or move, with the document declaring it.

type Rename added in v0.4.2

type Rename struct {
	// Target is the element to rename, named as Symbol.ID names it.
	Target string
	// NewName is the new declared name; it must lex as an identifier.
	NewName string
}

Rename rewrites a declaration's name token. References are not updated: a rename of a referenced element is refused, naming what refers to it.

type RenderCanvas added in v0.10.0

type RenderCanvas struct {
	Unit    string
	Width   float64
	Height  float64
	HasSize bool
}

RenderCanvas is the optional canvas bounds for a view.

type RenderEdge added in v0.10.0

type RenderEdge struct {
	From     string
	To       string
	FromPort string
	ToPort   string
	Label    string
	Name     string
	Kind     string
	Origin   *Span
	Route    []RenderPoint
	Style    *RenderStyle
}

RenderEdge is a connection between rendered nodes.

type RenderGeometry added in v0.10.0

type RenderGeometry struct {
	X         float64
	Y         float64
	Width     float64
	Height    float64
	HasSize   bool
	Collapsed bool
	Unplaced  bool
}

RenderGeometry is a node's position and optional size; an Unplaced one only folds or hides the node, its X and Y carrying no position.

type RenderNode added in v0.10.0

type RenderNode struct {
	ID              string
	Kind            string
	Name            string
	NameSynthesized bool
	Type            string
	Detail          string
	Text            string
	StandIn         bool
	Parent          string
	// Compartment names the compartment of Parent this node is a row of
	// ("attributes", "parts", "ports", ...); empty for a node drawn as a box.
	Compartment string
	Ports       []RenderPort
	Origin      *Span
	Geometry    *RenderGeometry
	Style       *RenderStyle
}

RenderNode is a view node with optional geometry and style.

type RenderNote added in v0.10.0

type RenderNote struct {
	Text     string
	Anchor   string
	EdgeFrom string
	EdgeTo   string
	X        float64
	Y        float64
	Width    float64
	Height   float64
	HasSize  bool
	Origin   *Span
}

RenderNote is an annotation in a rendered view.

type RenderPoint added in v0.10.0

type RenderPoint struct {
	X float64
	Y float64
}

RenderPoint is a point on an edge route.

type RenderPort added in v0.10.0

type RenderPort struct {
	ID        string
	Name      string
	Type      string
	Direction string
}

RenderPort is a port shown on a rendered node.

type RenderRow added in v0.10.0

type RenderRow struct {
	Cells  []string
	Origin *Span
}

RenderRow is one row of a table-style view.

type RenderStyle added in v0.10.0

type RenderStyle struct {
	Fill     string
	Line     string
	Text     string
	Font     string
	FontSize float64
	Bold     bool
	Italic   bool
}

RenderStyle is a rendered node or edge's optional style.

type RenderViewOption added in v0.10.0

type RenderViewOption func(*renderViewOptions)

RenderViewOption configures a view rendering.

func WithCompartments added in v0.11.0

func WithCompartments(folding string) RenderViewOption

WithCompartments folds a tree rendering's owned members into compartment rows of their owner: "positioned" (the default) folds only the layout-less members of a tree some Layout positions, "most" every owned usage no Layout, nested definition or package keeps a node, "ports" the port usages with the ports nested under them. A row is a node whose Compartment names the compartment of its Parent it is drawn in; another name is refused as an invalid request naming the foldings there are.

func WithDepth added in v0.11.0

func WithDepth(depth int) RenderViewOption

WithDepth draws this many levels of nested elements below each exposed element, overriding the view's own depth; zero draws every level the view allows.

func WithFullPorts added in v0.10.0

func WithFullPorts() RenderViewOption

WithFullPorts includes ports whether or not a connector uses them.

func WithShow added in v0.11.0

func WithShow(elements ...string) RenderViewOption

WithShow draws the named optional notation elements besides those the view's rendering shows: "parameter-symbols", "port-symbols", "compartments", "edge-labels", "keywords", "multiplicities", "typings", "qualifiers" or "all". The result's Shown lists the ones drawn; a name none of them has is refused as an invalid request naming the elements there are.

type RenderedView added in v0.10.0

type RenderedView struct {
	View    string
	Kind    string
	Stated  string
	Nodes   []RenderNode
	Edges   []RenderEdge
	Columns []string
	Rows    []RenderRow
	Canvas  *RenderCanvas
	Notes   []RenderNote
	Notices []string
	// Shown lists the optional notation elements drawn, the view's own and
	// those WithShow asked for.
	Shown []string
}

RenderedView is the lossless diagram data returned for a declared or targeted pseudo-view.

type Row added in v0.4.2

type Row struct {
	// Element is the element the row is about: for an object row, the usage the
	// object is held under; for a row a `Verdicts` query answered, the assertion
	// checked.
	Element Element
	// Object is the object a row over held objects is about — one an `Objects`
	// query enumerated or a bound object's part — nil for any other row.
	Object *Object
	// Verdict is the verdict a row a `Verdicts` query answered carries; nil for
	// any other row.
	Verdict *DocumentVerdict
	// State is the state a row a `States` query answered carries; nil for any
	// other row.
	State *DocumentState
	// Event is the trace record a row an `Events` query answered carries; nil
	// for any other row.
	Event *DocumentEvent
	// Cells holds each column's values, in column order.
	Cells [][]Cell
}

Row is one selected element and its projected cells, one per column.

type Rows added in v0.4.2

type Rows struct {
	// Columns are the projected properties in projection order.
	Columns []string
	// Rows are the selected elements and their cells.
	Rows []Row
}

Rows is a document query's answer: its projected columns, and one row per selected element, both in the order the engine reports.

type RunCountedValue added in v0.11.0

type RunCountedValue struct {
	Value Value
	Count int64
}

RunCountedValue counts the runs that observed one distinct value.

type RunDistribution added in v0.11.0

type RunDistribution struct {
	Name, Unit     string
	Count          int64
	Numeric        bool
	Min, Max, Mean Value
	Deviation      float64
	Percentiles    []RunPercentile
	Histogram      []RunHistogramBin
	Values         []RunCountedValue
}

RunDistribution summarises one observable over the completed runs: the extremes, mean, deviation, percentiles and histogram of a numeric one, or the count of each distinct value otherwise.

type RunHistogramBin added in v0.11.0

type RunHistogramBin struct {
	Low, High Value
	Count     int64
}

RunHistogramBin counts the runs whose value fell in [Low, High).

type RunPercentile added in v0.11.0

type RunPercentile struct {
	Percentile float64
	Value      Value
}

RunPercentile is the value a percentile of the runs fell at or below.

type RunRow added in v0.11.0

type RunRow struct {
	Inputs   []CalcOutput
	Outputs  []CalcOutput
	Verdicts []Verdict
	Error    string
}

RunRow is one run: the run number it bound, what it observed, what it decided, and the error that stopped it where it failed.

type Runs added in v0.11.0

type Runs struct {
	// Rows is the table, one per run in run order.
	Rows []RunRow
	// Observables names what every row reports, in column order.
	Observables []string
	// Distributions summarises each observable over the completed runs.
	Distributions []RunDistribution
	// Lines is the report as `sysml -runs` prints it.
	Lines []string
	// Outputs and Verdicts are a Monte Carlo case's conclusion over the sample;
	// Unconcluded says why it has none.
	Outputs     []CalcOutput
	Verdicts    []Verdict
	Unconcluded string
	Instances   []*Instance
	Standing    Standing
	// Seed is the seed the runs drew from, nil when the draws were fixed.
	Seed        *uint64
	Diagnostics []Diagnostic
}

Runs is what RunAction and RunMonteCarlo answer: one row per run, each observable's distribution over the completed runs and, for a Monte Carlo case, its conclusion over the sample.

func (*Runs) String added in v0.11.0

func (r *Runs) String() string

String is the report as `sysml -runs` prints it.

type RunsOption added in v0.11.0

type RunsOption func(*runsOptions)

RunsOption configures RunAction and RunMonteCarlo.

func RunsArgument added in v0.11.0

func RunsArgument(name string, value Value) RunsOption

RunsArgument binds one of the case's in parameters by name.

func RunsArguments added in v0.11.0

func RunsArguments(values ...Value) RunsOption

RunsArguments binds the case's in parameters positionally.

func RunsClockStep added in v0.11.0

func RunsClockStep(step float64) RunsOption

RunsClockStep sets the clock step of each run; zero keeps the default.

func RunsDraws added in v0.11.0

func RunsDraws(policy string) RunsOption

RunsDraws sets the draw policy for the model's distributions: "random" (the default), "min", "max" or "average".

func RunsEngine added in v0.11.0

func RunsEngine(name string) RunsOption

RunsEngine selects the analysis engine asked; empty is auto.

func RunsInputs added in v0.11.0

func RunsInputs(inputs map[string]Value) RunsOption

RunsInputs binds the action's input parameters before every run.

func RunsObserve added in v0.11.0

func RunsObserve(features ...string) RunsOption

RunsObserve names the action's features each run reports, "clock" for the time it completed at; none reports every feature and the clock.

func RunsPerformer added in v0.11.0

func RunsPerformer(symbolID string) RunsOption

RunsPerformer names the part/usage, or a path from one, whose object performs the action.

func RunsSeed added in v0.11.0

func RunsSeed(seed uint64) RunsOption

RunsSeed seeds the runs' draws, one derived seed per run; required unless RunsDraws fixes them.

func RunsSubject added in v0.11.0

func RunsSubject(symbolID string) RunsOption

RunsSubject names the part/usage to instantiate as the case's subject.

type Satisfaction added in v0.4.2

type Satisfaction struct {
	// Verdicts is one verdict per assertion evaluated, each carrying the body
	// verdicts of its own requirement.
	Verdicts []Verdict
	// Verifications are the body verdicts of every requirement the response
	// covers, each naming the requirement it was reported for.
	Verifications []VerificationVerdict
	// Instances are the objects the verdicts are about, each reported once.
	Instances []*Instance
	// Diagnostics the verification reported.
	Diagnostics []Diagnostic
}

Satisfaction is the verdict of each satisfaction assertion evaluated, in declaration order. A model stating none answers with no verdicts.

func (*Satisfaction) Holds added in v0.4.2

func (s *Satisfaction) Holds() bool

Holds reports whether every assertion was decided and held. A model stating no assertion holds trivially.

type SelfCheck added in v0.11.0

type SelfCheck struct {
	// Status is "holds", "fails" or "unresolved".
	Status                                                      string
	Findings                                                    []SelfCheckFinding
	Elements, Checks, Violations, Unevaluated, EvaluationErrors int64
	// Applications is how many elements each constraint was applied to.
	Applications map[string]int64
	// Summary is the one-line total `sysml -self-check` prints last.
	Summary     string
	Diagnostics []Diagnostic
}

SelfCheck is what SelfCheck answers: every finding of the reflective validation check and the counts over them.

func (*SelfCheck) Holds added in v0.11.0

func (s *SelfCheck) Holds() bool

Holds reports whether the check found no violation and no evaluation error.

type SelfCheckFinding added in v0.11.0

type SelfCheckFinding struct {
	Status, Subject, Location, Constraint, Element, Message, Line string
}

SelfCheckFinding is one violation, evaluation the runtime could not make, error or skipped rule constraint; Line is it as the CLI prints it.

type Sequence

type Sequence []Value

Sequence is an ordered collection of values.

type ServerInfo

type ServerInfo struct {
	// Version is the build version, informational only: feature decisions
	// belong on Capabilities.
	Version string
	// Capabilities are the named capabilities this implementation supports.
	Capabilities []string
}

ServerInfo describes the implementation answering a Client's calls.

func (*ServerInfo) Has

func (si *ServerInfo) Has(capability string) bool

Has reports whether the implementation names the capability. Negotiate on capabilities, not on versions; preflight gives a clearer error than waiting for a capability-gated request to be refused.

type Session added in v0.9.0

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

Session is a persistent, interactive run of one model: it keeps a clock, a scheduling policy and the objects it instantiated across calls, so a caller can instantiate a part, send its state machine a signal, perform an action on it and read what changed, one step at a time. Sessions are answered in process only — see OpenSession — and are not part of the Client interface. A Session is safe for concurrent use; every call is answered before it returns, bounded by the same step budget as ExecuteAction.

func OpenSession added in v0.9.0

func OpenSession(c Client, model *Model) (*Session, error)

OpenSession opens a Session over a model the client parsed. Only a client New returned can answer: a session is state the engine holds between calls, which the service exposes no RPC for, so a Dial client answers CodeUnimplemented. The model must still be in the client's cache (CodeNotFound otherwise); the session then holds it for as long as it lives.

func (*Session) Accepts added in v0.9.0

func (s *Session) Accepts(object InstanceID, signalID string, args map[string]Value) (acceptance *Acceptance, err error)

Accepts says what sending the signal to the object would do now, without sending it: which machines it exhibits would take it, whether a transition of theirs, an enclosing state's included, is triggered by it and whether a guard holds. The signal definition is named by ID; args bind its attributes.

func (*Session) ActiveStates added in v0.9.0

func (s *Session) ActiveStates(object InstanceID) (states []string, err error)

ActiveStates names the innermost active states of every state machine the object exhibits, machine by machine in declaration order, one per active region; the composite states enclosing them are active too. A FailureError when the object exhibits none.

func (*Session) Advance added in v0.9.0

func (s *Session) Advance(seconds float64) (advanced *Advancement, err error)

Advance moves the clock forward by seconds — zero to dispatch what is posted now — running the transitions, effects and completion transitions that follow until the machines settle.

func (*Session) Close added in v0.9.0

func (s *Session) Close() error

Close ends the session and releases what it holds. Every later call answers CodeUnavailable; closing twice is harmless.

func (*Session) Evaluate added in v0.9.0

func (s *Session) Evaluate(expression string, opts ...EvaluateOption) (value Value, err error)

Evaluate evaluates one expression against the session's state, resolving its names in the scope WithContextSymbol names, or the model's primary document when none is given. A feature of an object the session holds reads that object's current value. WithSubject is not taken: the session's objects are the subjects.

func (*Session) Feature added in v0.9.0

func (s *Session) Feature(object InstanceID, name string) (value *FeatureValue, err error)

Feature reads what an object holds for one feature of its type, by name, as the session's runs have left it.

func (*Session) Instantiate added in v0.9.0

func (s *Session) Instantiate(symbolID string) (id InstanceID, err error)

Instantiate creates an object of the named part or usage, starting the state machines it exhibits, and answers the handle later calls take. The object lives until the session closes.

func (*Session) Members added in v0.9.0

func (s *Session) Members(symbolID string) (members []Member, err error)

Members lists the named members of the named package, definition or usage, in declaration order: the literals of an enumeration, the parts of a package.

func (*Session) Now added in v0.9.0

func (s *Session) Now() (now float64, err error)

Now is the session's clock, in seconds since it opened.

func (*Session) Perform added in v0.9.0

func (s *Session) Perform(object InstanceID, actionID string, inputs map[string]Value) (performed *Performance, err error)

Perform performs the named action on the object, binding inputs to its in parameters, and runs it to completion in the session's state; the object's features read and written by the action are those the session holds. A run the model fails is a FailureError carrying the run's diagnostics.

func (*Session) Send added in v0.9.0

func (s *Session) Send(object InstanceID, signalID string, args map[string]Value) (acceptance *Acceptance, err error)

Send posts the signal to the object; Advance then dispatches it and runs what follows, completion transitions included. A signal no machine the object exhibits would take, or one every taking machine would drop because its guards are false, is refused with CodeFailedPrecondition and nothing is posted.

func (*Session) SetFeature added in v0.9.0

func (s *Session) SetFeature(object InstanceID, name string, value Value) error

SetFeature writes one feature of an object, as an assignment in the model would.

func (*Session) SetSchedule added in v0.9.0

func (s *Session) SetSchedule(policy string) error

SetSchedule makes the session's later turns resolve their choice points under the policy, as sysml -schedule spells it ("seed:42"): the actions it performs from now on, and the objects' machines and the clock from their next step on, their states and pending signals kept. "explore[...]" is refused, an exploration replays whole runs. Setting the same seed again restarts its stream, so two turns from the same seed choose alike.

func (*Session) Transitions added in v0.9.0

func (s *Session) Transitions(object InstanceID) (transitions []Transition, err error)

Transitions lists the transitions dispatch could select now, machine by machine: those out of each active state and then of each state enclosing it, innermost first as dispatch tries them, each in declaration order. A caller offers them as what the object could do next; Source tells which state declares each.

type Set added in v0.7.0

type Set []Value

Set is a unique, unordered collection — a Collections::Set's elements — as distinct from a Sequence, whose order is part of its value. The service sends the elements in its canonical order, so equal sets arrive alike; a caller may list them in any order, but one listing an element twice, by Equal, is refused when sent rather than read as one element.

func (Set) Contains added in v0.7.0

func (s Set) Contains(value Value) bool

Contains reports whether value is a member of the set.

func (Set) String added in v0.7.0

func (s Set) String() string

String renders the set as SysML traces format it: `{1, 2, 3}`, the elements in the order held.

type SetValue added in v0.4.2

type SetValue struct {
	// Target is the element to edit, named as Symbol.ID names it.
	Target string
	// Value is the new value in SysML notation ("1050.0[SI::kg]", "mass * 2").
	Value string
}

SetValue sets the value of a feature that already exists, replacing the expression of its `= <expr>` or adding one before the declaration's `;`.

type Span

type Span struct {
	File      string
	StartLine int
	StartCol  int
	EndLine   int
	EndCol    int
}

Span is a source location.

type Specialization

type Specialization struct {
	// Kind of relationship: "specializes", "subsets", "redefines" or "typing".
	Kind string
	// Declared is the target as written ("Engine", "Demo::Engine").
	Declared string
	// TargetID is the FQN of the resolved target; empty when unresolved.
	TargetID string
	// TargetKind is the symbol kind of the resolved target; empty when
	// unresolved.
	TargetKind string
}

Specialization is one generalization edge an element declares.

type Standing added in v0.8.0

type Standing struct {
	// Engine is the engine that answered, as ListEngines names it.
	Engine string
	// Strength is "not covered", "observed", "witnessed", "bounded" or "proved".
	Strength string
	// Bounds are the bounds the answer ran under.
	Bounds []Bound
}

Standing is how strongly an answer stands: the engine that answered, the strength of its evidence and the bounds it ran under. Zero from a service without CapabilityEngines.

type StateRun added in v0.4.2

type StateRun struct {
	// Visited is the trace of states entered, in order.
	Visited []string
	// Context is the machine's context when execution stopped, by feature name.
	Context map[string]Value
	// FinalTime is the run's simulation clock when it ended, in seconds from
	// the 0 it started at; 0 from a service without CapabilityFinalTime.
	FinalTime float64
	// Trace is the documented execution record sequence, when requested.
	Trace []DocumentEvent
	// TraceDropped is the number of oldest trace records the service discarded.
	TraceDropped int
	// Diagnostics the execution reported.
	Diagnostics []Diagnostic
}

StateRun is what one state machine execution produced.

type StatisticDifference added in v0.11.0

type StatisticDifference struct {
	Min, Mean, P50, P90, Max string
}

StatisticDifference is the relative difference of each statistic as a signed percentage, "" where it is not compared.

type StatusError

type StatusError struct {
	// Code says why the call was refused.
	Code Code
	// Message is the service's own wording.
	Message string
}

StatusError is a call the service refused: the transport-level failure a remote caller would see as a gRPC status. errors.Is(err, opensysml.CodeX) matches the code, and errors.As recovers the message.

func (*StatusError) Error

func (e *StatusError) Error() string

Error renders the refusal with its canonical code name. Code.String is spelled out because a Code is itself an error, which fmt would render with Error instead.

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

Unwrap exposes the Code, so errors.Is(err, opensysml.CodeNotFound) matches.

type String

type String string

String is a string value.

type Symbol

type Symbol struct {
	// ID is the fully qualified name, the identifier the other calls take.
	ID   string
	Name string
	// Kind of the element ("PartDefinition", "AttributeUsage", …).
	Kind     string
	Metadata map[string]string
	// ChildIDs are the fully qualified names of the element's children.
	ChildIDs []string
	// Attributes of the element, absent without the symbol_attributes
	// capability.
	Attributes []Attribute
	// Type facts, nil when the element is not a def/usage or the type_facts
	// capability is absent.
	Type *TypeInfo
	// Multiplicity as declared, nil when none is declared.
	Multiplicity *Multiplicity
	// Specializations are every generalization edge declared, in declaration
	// order.
	Specializations []Specialization
	// WithheldLibraryAttributes counts attributes inherited from
	// standard-library content, which Attributes leaves out.
	WithheldLibraryAttributes int
}

Symbol is one element of a parsed model.

type TensorQuantity added in v0.7.0

type TensorQuantity struct {
	// Dimensions are the positive extents, one per rank.
	Dimensions []int64
	// Components fill the dimensions in row-major order.
	Components []Quantity
}

TensorQuantity is a tensor quantity of any rank: one Quantity per component, unit and reduction included, in row-major order under its dimensions. A tensor of rank one is not a VectorQuantity, here as in the runtime.

func (TensorQuantity) String added in v0.7.0

func (tq TensorQuantity) String() string

String renders the tensor as SysML formats it: `Tensor(2, 2, 2)[1.0, 2.0, ...] m` when every component shares a unit, else each component with its own.

type ToolDryRun added in v0.11.0

type ToolDryRun struct {
	// Action is the FQN of the ToolExecution-annotated step reached.
	Action string
	// Tool, Version and Manifest identify the manifest entry the step resolved to.
	Tool, Version, Manifest string
	// Executable and Args are the program and arguments; Env its added
	// environment and Cwd its working directory.
	Executable string
	Args, Env  []string
	Cwd        string
	// Protocol is how the tool is spoken to; Stdin and StdinData what it
	// would read; InputFile the file it would be handed, if any.
	Protocol, Stdin, StdinData string
	InputFile                  *ToolDryRunFile
	// OutputDir reports whether an output directory would be created.
	OutputDir bool
	// Inputs and Outputs are the values handed over and asked for.
	Inputs  []ToolDryRunInput
	Outputs []ToolDryRunOutput
	// ReplySource says where the reply would be read from.
	ReplySource string
	// Lines is the preview the sysml command prints.
	Lines []string
}

ToolDryRun is the first external tool call an analysis would have made, as sysml -tool-dry-run previews it.

type ToolDryRunFile added in v0.11.0

type ToolDryRunFile struct {
	Name, Format, Data string
}

ToolDryRunFile is the input file a dry run would hand the tool.

type ToolDryRunInput added in v0.11.0

type ToolDryRunInput struct {
	Variable, Parameter, Value, Unit string
}

ToolDryRunInput is one value the tool would be handed: the tool's variable, the case parameter it is bound to, the rendered value and its unit.

type ToolDryRunOutput added in v0.11.0

type ToolDryRunOutput struct {
	Variable, Parameter string
}

ToolDryRunOutput is one value the tool would be asked for.

type Transition added in v0.9.0

type Transition struct {
	// Name of the transition, "" when it was declared anonymously.
	Name string
	// Source and Target name the states the transition joins.
	Source string
	Target string
	// Trigger says what fires it.
	Trigger TriggerKind
	// Signal is the simple name of the signal type a TriggerSignal transition
	// accepts, "" when it accepts by event feature instead or for the other kinds.
	Signal string
	// Event is the feature path an accept trigger subsets (`alert`,
	// `left.alert`) when it accepts an occurrence of that event feature rather
	// than a signal type, "" otherwise.
	Event string
	// Guarded reports whether a guard stands on it; Accepts says whether the
	// guard holds now.
	Guarded bool
}

Transition is one transition of a state machine, as declared: which states it joins, what fires it and whether a guard stands on it.

type TriggerKind added in v0.9.0

type TriggerKind string

TriggerKind says what fires a Transition.

const (
	// TriggerCompletion fires when the source state's entry behavior completes.
	TriggerCompletion TriggerKind = sysmlgrpc.TriggerCompletion
	// TriggerSignal fires on accepting a signal: one of the type
	// Transition.Signal names, or an occurrence of the event feature
	// Transition.Event names.
	TriggerSignal TriggerKind = sysmlgrpc.TriggerSignal
	// TriggerTime fires when a time event is due.
	TriggerTime TriggerKind = sysmlgrpc.TriggerTime
	// TriggerChange fires when a change event's condition comes true.
	TriggerChange TriggerKind = sysmlgrpc.TriggerChange
	// TriggerCall fires on a call event.
	TriggerCall TriggerKind = sysmlgrpc.TriggerCall
)

The kinds of trigger a Transition reports.

type TypeInfo

type TypeInfo struct {
	// Declared is the type name as written; empty when none is declared.
	Declared string
	// ResolvedID is the FQN of the resolved type; empty when unresolved.
	ResolvedID string
	// ResolvedKind is the symbol kind of the resolved type ("partDef", …).
	ResolvedKind string
	// Primitive is the library scalar the type reduces to ("Boolean",
	// "Integer", "Real", …); empty when it is not a scalar value type.
	Primitive string
	// PrimitiveSource is the origin of Primitive: "declared", "value", or
	// empty.
	PrimitiveSource string
	// Quantity reports that values carry a measurement unit.
	Quantity bool
	// Unit as written when the default value names one ("m/s"), else empty.
	Unit string
}

TypeInfo is the static type of a usage, or the classification of a definition, as far as the service derives it without running the model.

type Undetermined added in v0.8.0

type Undetermined struct {
	// Reason says why the model fixes no answer: "u has no value in the model".
	Reason string
	// CountLower and CountUpper bound how many values the result would hold, as
	// MultiplicityInfo spells them: "1"/"1" for a scalar, "1"/"*" for a [1..*] feature.
	CountLower, CountUpper string
}

Undetermined is a model-level result the model leaves open (an unbound feature, an unfixed count): a successful answer, reported, never accepted.

func (Undetermined) String added in v0.8.0

func (Undetermined) String() string

String reports a result the model leaves open, as every other surface spells it.

type UnitFactor

type UnitFactor struct {
	// UnitID is the FQN of the base unit ("SI::m").
	UnitID string
	// Exponent the base unit is raised to.
	Exponent float64
}

UnitFactor is one base unit raised to an exponent.

type UnitTerm

type UnitTerm struct {
	ScaleNum float64
	ScaleDen float64
	// Factors are the base units of the reduction, carrying no zero exponents.
	Factors []UnitFactor
}

UnitTerm is a unit's reduction to base units, with its scale kept as an unevaluated ratio so an exact conversion stays exact.

func (UnitTerm) String added in v0.6.0

func (t UnitTerm) String() string

String renders the reduction over its base units, `1000/3600·SI::m·SI::s^-1`, a scale of one and an exponent of one left implicit; `1` for dimension one.

type Unset

type Unset struct{}

Unset is a valueless feature of a value type: materialized, holding no value. It is reported, never accepted.

func (Unset) String added in v0.4.2

func (Unset) String() string

String reports a materialized feature holding no value.

type Validation added in v0.9.0

type Validation struct {
	// Verdicts is one verdict per assertion per object, in the order the objects
	// were reached from the validated one, each naming its object by InstancePath.
	Verdicts []Verdict
	// Summary is the verdict about the object as a whole, of Kind "object": it
	// holds when every verdict holds and every held object was reached, and is
	// Undecided, with the reason as its Error, when an assertion is.
	Summary *Verdict
	// Verifications are the body verdicts of every requirement the verdicts are
	// about, each naming the requirement it was reported for.
	Verifications []VerificationVerdict
	// Instances are the objects reachable from the validated one, including it.
	Instances []*Instance
	// Bounded reports a walk cut short by an object graph that goes on without
	// end, so objects past the cut carry assertions no verdict covers.
	Bounded bool
	// Diagnostics the validation reported.
	Diagnostics []Diagnostic
}

Validation is every assertion's verdict about one object and the objects it holds: its asserted constraints and invariants, the requirements it carries, and the satisfaction assertions whose subjects are inside it.

func (*Validation) Valid added in v0.9.0

func (v *Validation) Valid() bool

Valid reports whether the object stands: at least one assertion, every one held and every held object reached. An undecided assertion, a bounded walk or an object no assertion is about is not valid.

func (*Validation) Violated added in v0.9.0

func (v *Validation) Violated() bool

Violated reports whether an assertion answered false, whatever else went undecided.

type Value

type Value interface {
	// contains filtered or unexported methods
}

Value is one evaluated SysML value. It is a sealed sum: the concrete types are Int, BigInt, Rational, Real, Complex, Bool, String, InstanceID, Sequence, Null, Unset, Quantity, EnumLiteral, Array, Vector, VectorQuantity, MeasurementRef, Function, Set, TensorQuantity, Metaobject and Undetermined, and a type switch over them is exhaustive.

type Vector added in v0.6.0

type Vector []Number

Vector is a numerical vector: its components in order, each an Int or a Real, kept apart as the rest of Value does. Its dimension is the number of them.

func (Vector) String added in v0.6.0

func (v Vector) String() string

String renders the vector as SysML formats it: `⟨3.0, 4.0⟩`.

type VectorQuantity added in v0.6.0

type VectorQuantity []Quantity

VectorQuantity is a vector quantity: one Quantity per axis, unit and reduction included, since the axes need not share a unit.

func (VectorQuantity) String added in v0.6.0

func (vq VectorQuantity) String() string

String renders the vector quantity as SysML formats it: `⟨3.0, 4.0⟩ m` when every axis shares a unit, else each component with its own.

type Verdict added in v0.4.2

type Verdict struct {
	// Kind is what was verified: "constraint", "requirement" or "satisfy".
	Kind string
	// ElementID is the FQN verified, empty for an anonymous satisfy assertion.
	ElementID string
	// Element is the element as a reader names it, or the assertion as written.
	Element string
	// Holds is the model's answer. False with an empty Error is a verdict of
	// false; false with an Error is no verdict at all — see Undecided.
	Holds bool
	// Condition is the condition that evaluated to false, as written, when the
	// runtime names one.
	Condition string
	// InstanceID is the object the verdict is about, 0 when it is about declared
	// values alone. Verification.Instances carries its feature values.
	InstanceID int64
	// InstanceTypeID is the FQN of that object's type.
	InstanceTypeID string
	// Error is set when evaluation failed rather than the model answering false.
	Error string
	// Reason says what kind of failure Error reports.
	Reason Reason
	// RequirementID is the FQN of the requirement a satisfaction verdict
	// asserts satisfied, empty when the assertion names none.
	RequirementID string
	// InstancePath names the object the verdict is about by the features held
	// from the validated object, "engine.pump" or "wheels[2]"; empty for the
	// validated object itself and for verdicts a Validation did not produce.
	InstancePath string
	// Verifications are the body verdicts of that requirement's verification
	// cases, reported beside this verdict rather than instead of it.
	Verifications []VerificationVerdict
	// Question is the question the verdict answers: "evaluate" for an
	// evaluation, reported by a service advertising
	// CapabilityVerificationQuestions and empty from one predating it.
	Question string
	// Status is the answer's status: holds | violated | undecided |
	// satisfiable | unsatisfiable, as the service spells it.
	Status string
	// Witness is the assignment witnessing the answer: the free features' values
	// for a violated holds question or a satisfiable satisfiable question.
	Witness []WitnessAssignment
	// Notes is what the answer rests on — the features read as one value or
	// object while only the default multiplicity governs them, and the
	// object-holding features whose own assertions the question does not
	// state — in report order; empty from a service without verdict_notes.
	Notes []VerdictNote
	// Standing is how strongly the verdict stands: the engine that answered, the
	// strength of its evidence and the bounds it ran under.
	Standing Standing
}

Verdict is one verification's answer: whether the condition held, and, when it did not, what the model answered false about.

func (*Verdict) Undecided added in v0.4.2

func (v *Verdict) Undecided() bool

Undecided reports a verdict that is no answer about the model: evaluation failed instead of the condition holding or not.

type VerdictKind added in v0.7.0

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.
	VerdictInconclusive VerdictKind = "inconclusive"
	// VerdictError is a body whose run could not be carried out.
	VerdictError VerdictKind = "error"
)

The verdicts a verification case's body produces.

type VerdictNote added in v0.12.0

type VerdictNote struct {
	// Kind is NoteAssumedOne or NoteUncovered.
	Kind string
	// Subject names the feature the note is about, as the report quotes it.
	Subject string
	// Text is the note as a sentence.
	Text string
}

VerdictNote is one assumption or omission behind a Verdict, worded as every surface reports it.

type Verification added in v0.4.2

type Verification struct {
	// Verdict is the answer.
	Verdict *Verdict
	// Verifications are the body verdicts of the verification cases verifying
	// this requirement, empty for a constraint and for a service reporting none.
	Verifications []VerificationVerdict
	// Instances are the objects reachable from the verdict's subject, including
	// it, so its feature values need no follow-up call.
	Instances []*Instance
	// Diagnostics the verification reported.
	Diagnostics []Diagnostic
}

Verification is one constraint's or requirement's verdict, with the objects it is about.

type VerificationVerdict added in v0.7.0

type VerificationVerdict struct {
	// CaseID is the FQN of the verification case that ran.
	CaseID string
	// Kind is the VerdictKind the body produced.
	Kind VerdictKind
	// Detail is the text of an error verdict, or why an inconclusive one
	// decided nothing; empty for a pass and a fail.
	Detail string
	// Subcase marks the verdict of a case another performed, which the library
	// states no roll-up for and which is therefore reported on its own.
	Subcase bool
	// RequirementID is the FQN of the requirement this verdict was reported
	// for, empty when the case ran for itself rather than for a requirement.
	RequirementID string
	// InstanceID is the ID of the object the case ran on as its owner, 0 when
	// it ran on none; its feature values are in the response's Instances.
	InstanceID int64
	// InstanceTypeID is the FQN of that object's type.
	InstanceTypeID string
}

VerificationVerdict is what the body of a verification case answered when it ran, which is a separate answer from whether a requirement is satisfied. Reported by a service advertising CapabilityVerificationVerdicts.

type VerifyError added in v0.4.2

type VerifyError struct {
	FailureError
	// Reason says what kind of failure this is, so a caller acts on the kind.
	Reason Reason
}

VerifyError is a verification or calculation the service could not answer at all, classified: an undecided verdict about the model arrives as a Verdict instead. It is a FailureError, so errors.Is(err, ErrFailure) matches.

func (*VerifyError) Unwrap added in v0.4.2

func (e *VerifyError) Unwrap() error

Unwrap exposes the failure, so errors.As recovers a *FailureError from a classified one.

type VerifyOption added in v0.4.2

type VerifyOption func(*verifyOptions)

VerifyOption configures VerifyConstraint and VerifyRequirement.

func Against added in v0.4.2

func Against(symbolID string) VerifyOption

Against names a part or usage to instantiate and verify against, so the verdict is about that object's values rather than declared defaults. It is what WithSubject is to Evaluate.

func Asking added in v0.9.2

func Asking(question string) VerifyOption

Asking names the question a verification answers: QuestionEvaluate (the default), QuestionHolds or QuestionSatisfiable. A question other than evaluate requires the verification_questions capability, checked before anything is sent.

func VerifyArgument added in v0.10.0

func VerifyArgument(name string, value Value) VerifyOption

VerifyArgument binds the `in` parameter named, as Argument binds a case's.

func VerifyArguments added in v0.10.0

func VerifyArguments(values ...Value) VerifyOption

VerifyArguments bind the constraint's or requirement's `in` parameters in declaration order, as Arguments binds a case's. Binding any requires the verification_arguments capability, checked before anything is sent; a proof question takes none.

func WithEngine added in v0.8.0

func WithEngine(engine string) VerifyOption

WithEngine names the engine that answers a verification, as `sysml -engine` spells it: an engine's name, EngineAuto or EngineAll. Requires the engines capability, checked before anything is sent.

type WitnessAssignment added in v0.9.2

type WitnessAssignment struct {
	// Feature is the qualified feature name, chain steps appended with '.'.
	Feature string
	// Value is the value the evaluator replayed for the feature.
	Value Value
	// Unit names the base units the magnitude is expressed in, empty for a
	// value that has none.
	Unit string
	// Exact is the solver's exact value as text.
	Exact string
}

WitnessAssignment is one feature's value in the assignment witnessing a violated holds question or a satisfiable satisfiable question: the value the evaluator replayed, in the base units reported, and the solver's exact spelling of it.

Jump to

Keyboard shortcuts

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