opensysml

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: Apache-2.0 Imports: 11 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/client/opensysml is the Go surface of OpenSysML: parse SysML v2 models, look up symbols, evaluate expressions and instantiate parts, from Go code, using the engine already linked into the calling binary.

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")

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/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. 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

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).

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 seven operations, New, Dial, the option functions, the error model (Code, StatusError, FailureError, ErrFailure), and the data types they exchange. Changes will be additive.
  • Experimental: nothing currently. A future addition that is not yet a commitment will say so in its Godoc.

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

Explicitly out of v1, deliberately rather than half-implemented: generated model-ergonomics types, the edit API (ApplyEdits), RDF conversion (Convert), verification helpers (VerifyConstraint, VerifyRequirement, VerifySatisfaction), behavior execution (ExecuteAction, ExecuteState), calc evaluation (EvaluateCalc) and queries (Query). For those, use the generated stubs in api/proto / api/proto/protoconnect against a running service.

None of the v1 operations shells out to an SMT solver, so an in-process caller needs nothing installed. The verification RPCs are the ones that discover z3/cvc5 (or $OPENSYSML_SMT); when verification helpers arrive here, the package will document that requirement and report a missing solver in the verdict rather than failing the call.

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 ./cmd/conformance -protocols pkg,pkg-connect -allow-skips

Scenarios for RPCs outside the v1 surface are reported as skips, with the reason named per scenario in the report; nothing covered is skipped.

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

Examples

Constants

View Source
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

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

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 Bool

type Bool bool

Bool is a boolean 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

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 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 Int

type Int int64

Int is an integer value.

type Language

type Language string

Language selects the notation of inline content.

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

The languages ParseSource accepts.

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

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.

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

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 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 Real

type Real float64

Real is a real value.

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 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 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 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 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, Bool, String, InstanceID, Sequence, Null, Unset, Quantity and EnumLiteral, and a type switch over them is exhaustive.

Jump to

Keyboard shortcuts

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