Documentation
¶
Overview ¶
Package opensysml is the public Go API for OpenSysML: parse SysML v2 models, look up symbols, evaluate expressions and instantiate parts.
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")
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, 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 and the explicit list of what v1 leaves out (editing, conversion, verification, behavior execution, generated model types).
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
- type Attribute
- type Bool
- type Client
- type Code
- type Diagnostic
- type DialOption
- type EnumLiteral
- type EvaluateOption
- type FailureError
- type FeatureValue
- type Instance
- type InstanceID
- type Instantiation
- type Int
- type Language
- type Model
- type Multiplicity
- type Null
- type Number
- type Option
- type ParseOption
- type Quantity
- type Real
- type Sequence
- type ServerInfo
- type Span
- type Specialization
- type StatusError
- type String
- type Symbol
- type TypeInfo
- type UnitFactor
- type UnitTerm
- type Unset
- type Value
Examples ¶
Constants ¶
const ( CapabilityTypeFacts = sysmlgrpc.CapabilityTypeFacts CapabilityConvert = sysmlgrpc.CapabilityConvert CapabilityVerification = sysmlgrpc.CapabilityVerification CapabilityQuery = sysmlgrpc.CapabilityQuery CapabilityOSLCQuery = sysmlgrpc.CapabilityOSLCQuery 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 )
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.
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 ¶
This section is empty.
Types ¶
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 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)
// 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)
// Close releases what the implementation holds. The Client answers no
// further calls.
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.
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 Diagnostic ¶
type Diagnostic struct {
// Severity is "error", "warning" or "info".
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.
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 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.
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 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.
type Model ¶
type Model struct {
// Hash is the content-addressed cache key the service assigned the parse.
Hash string
// Root is the model's root namespace.
Root *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.
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 ParseFile and ParseSource.
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 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 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 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.
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.