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.
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.
No operation shells out to an SMT solver: verification evaluates conditions with the same runtime Evaluate and Instantiate use. The solver-backed analyses belong to the REPL.
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 ¶
- Constants
- Variables
- func CellText(cell Cell) string
- type ActionRun
- type AddMember
- type Analysis
- type AnalysisOption
- type AppliedEdit
- type Array
- type Attribute
- type Binding
- type Bool
- type CalcOutput
- type Calculation
- type Cell
- type Client
- type Code
- type Complex
- type Condition
- type Conversion
- type ConvertOption
- type Delete
- type Diagnostic
- type DialOption
- type Document
- type Edit
- type EditError
- type EditFailure
- type EditResult
- type Element
- type EnumLiteral
- type EvaluateOption
- type FailureError
- type FeatureValue
- type Format
- type Infinity
- type Instance
- type InstanceID
- type Instantiation
- type Int
- type Language
- type MeasurementRef
- type Model
- type Multiplicity
- type Null
- type Number
- type Option
- type ParseOption
- type Quantity
- type Query
- type QueryElement
- type Real
- type Reason
- type Rename
- type Row
- type Rows
- type Satisfaction
- type Sequence
- type ServerInfo
- type SetValue
- type Span
- type Specialization
- type StateRun
- type StatusError
- type String
- type Symbol
- type TypeInfo
- type UnitFactor
- type UnitTerm
- type Unset
- type Value
- type Vector
- type VectorQuantity
- type Verdict
- type Verification
- type VerifyError
- type VerifyOption
Examples ¶
Constants ¶
const ( CapabilityTypeFacts = sysmlgrpc.CapabilityTypeFacts CapabilityConvert = sysmlgrpc.CapabilityConvert CapabilityVerification = sysmlgrpc.CapabilityVerification CapabilityQuery = sysmlgrpc.CapabilityQuery CapabilityOSLCQuery = sysmlgrpc.CapabilityOSLCQuery CapabilityDocumentQuery = sysmlgrpc.CapabilityDocumentQuery CapabilityRenderDocument = sysmlgrpc.CapabilityRenderDocument CapabilityEnumValues = sysmlgrpc.CapabilityEnumValues CapabilityEvaluateSubject = sysmlgrpc.CapabilityEvaluateSubject CapabilitySymbolAttributes = sysmlgrpc.CapabilitySymbolAttributes CapabilityUnsetValue = sysmlgrpc.CapabilityUnsetValue CapabilityFeatureValues = sysmlgrpc.CapabilityFeatureValues CapabilityApplyEdits = sysmlgrpc.CapabilityApplyEdits CapabilityAuthoring = sysmlgrpc.CapabilityAuthoring CapabilityInlineLanguage = sysmlgrpc.CapabilityInlineLanguage CapabilityStrictConformance = sysmlgrpc.CapabilityStrictConformance CapabilityParseSources = sysmlgrpc.CapabilityParseSources CapabilityComplexValues = sysmlgrpc.CapabilityComplexValues CapabilityStructuredValues = sysmlgrpc.CapabilityStructuredValues CapabilityMeasurementRefs = sysmlgrpc.CapabilityMeasurementRefs )
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.
const ( SeverityError = "error" SeverityWarning = "warning" SeverityInfo = "info" )
The severities a Diagnostic reports.
Variables ¶
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 ¶
Types ¶
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
// Diagnostics the execution reported.
Diagnostics []Diagnostic
}
ActionRun is what one action execution produced.
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
}
AddMember inserts a declaration into a namespace or the document root.
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
// Instances are the objects reachable from the subject the run was given,
// including it; empty when the case bound its own subject.
Instances []*Instance
// Diagnostics the run reported.
Diagnostics []Diagnostic
}
Analysis is what one run of an analysis case produced.
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 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.
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
// 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.
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 Binding ¶ added in v0.4.2
Binding binds one entry parameter of a document query. Several values bind a nonscalar parameter.
type CalcOutput ¶ added in v0.4.2
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
// 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 Cell ¶ added in v0.4.2
type Cell interface {
// contains filtered or unexported methods
}
Cell is one typed document-query value: Element, String, Int, Real, Bool or Infinity. A type switch over them is exhaustive.
type Client ¶
type Client interface {
// ServerInfo reports the implementation's version and capabilities.
ServerInfo(ctx context.Context) (*ServerInfo, 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) ([]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 and a MeasurementRef
// input the measurement_refs one, checked before anything is sent.
ExecuteAction(ctx context.Context, model *Model, actionSymbolID string, inputs map[string]Value) (*ActionRun, error)
// ExecuteState runs the named state machine, feeding it the events in
// order, and reports the states visited and the context left behind.
ExecuteState(ctx context.Context, model *Model, stateMachineSymbolID string, events []string) (*StateRun, error)
// VerifyConstraint evaluates the named constraint, optionally Against a
// part to instantiate and check. Requires the verification capability.
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. Requires the verification capability.
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. Requires the
// verification capability.
VerifySatisfaction(ctx context.Context, model *Model, symbolID string) (*Satisfaction, 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 or
// measurement_refs capability for a Complex, a structured or a
// MeasurementRef argument, checked before anything is sent.
EvaluateCalc(ctx context.Context, model *Model, symbolID string, arguments ...Value) (*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. Requires the verification capability, and the complex_values or
// structured_values capability for a Complex or a structured argument,
// checked before anything is sent.
RunAnalysis(ctx context.Context, model *Model, symbolID string, opts ...AnalysisOption) (*Analysis, 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, 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)
// 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. 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. Requires the convert capability.
ConvertSource(ctx context.Context, content string, to Format, opts ...ConvertOption) (*Conversion, error)
// ApplyEdits answers the model's source with every edit applied, or refuses
// them all with an EditError. Requires the apply_edits capability, and a
// model of one document.
ApplyEdits(ctx context.Context, model *Model, 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 ¶
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 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.
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.
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, Greater, Less, All or Any, and negate it with Not.
func All ¶ added in v0.4.2
All matches an element every condition matches. An empty list fails the call: it has no defensible verdict.
func Any ¶ added in v0.4.2
Any matches an element at least one condition matches. An empty list fails the call.
func Equals ¶ added in v0.4.2
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.
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, whose vocabulary 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
}
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 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 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
// 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 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.
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.
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: SetValue, Rename, AddMember or Delete. A type switch over them 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.
Referring []string
}
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.
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) )
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 {
// Content is the edited notation, byte-identical to the source outside the
// edited spans.
Content string
// Applied says what each edit changed, in request order.
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 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.
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
}
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 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
}
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" )
The formats conversion accepts. There are two canonical ones, FormatSysML and FormatTTL, and a Conversion answers by those names whichever alias was asked for. RDF, in any spelling, is an experimental mapping, which a Conversion reports.
type Infinity ¶ added in v0.4.2
type Infinity struct{}
Infinity is an unbounded multiplicity. It is answered, never bound.
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 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 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
}
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.
type Multiplicity ¶
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.
type Number ¶
type Number interface {
Value
// contains filtered or unexported methods
}
Number is a Value that is a numeric magnitude: Int or Real. Integers and reals stay apart end to end, so an integer compares exactly.
type Option ¶
type Option func(*options)
Option configures New.
func WithCacheSize ¶
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 ParseOption ¶
type ParseOption func(*parseOptions)
ParseOption configures the parse calls.
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 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.
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
}
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 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) )
The failure kinds a verification or calculation reports.
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 Row ¶ added in v0.4.2
type Row struct {
// Element is the element the row is about.
Element Element
// 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 Satisfaction ¶ added in v0.4.2
type Satisfaction struct {
// Verdicts is one verdict per assertion evaluated.
Verdicts []Verdict
// 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 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 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 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 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
// Diagnostics the execution reported.
Diagnostics []Diagnostic
}
StateRun is what one state machine execution produced.
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 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 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 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.
type Unset ¶
type Unset struct{}
Unset is a valueless feature of a value type: materialized, holding no value. It is reported, never accepted.
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, Real, Complex, Bool, String, InstanceID, Sequence, Null, Unset, Quantity, EnumLiteral, Array, Vector, VectorQuantity and MeasurementRef, 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.
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
}
Verdict is one verification's answer: whether the condition held, and, when it did not, what the model answered false about.
type Verification ¶ added in v0.4.2
type Verification struct {
// Verdict is the answer.
Verdict *Verdict
// 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 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.