export

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 30 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package export saves a SysML v2 model to a file and converts between the two representations OpenSysML can write: SysML textual notation and RDF Turtle. It also reads a third, SysML v1 in XMI, which is migrated to v2 notation on the way in.

SysML output

Saving a model that came from source writes that source, re-indented by internal/syntax/format. Printing the AST instead would drop comments, notes and anything the parser recorded as an ErrorNode, so a save has to keep the token stream (see the format package doc).

RDF output

The graph uses the SysML vocabulary and element IRIs of the Flexo MMS SysML v2 service (https://www.omg.org/spec/SysML# and urn:sysmlv2:element:), so a converted model loads into that service's triplestore. Elements are addressed by qualified name (`urn:sysmlv2:element:Demo::Vehicle`), which makes the IRIs stable across conversions of the same model rather than newly generated each time.

Each element carries its metaclass as rdf:type and its declaration as SysML metamodel properties: declaredName, declaredShortName, owningNamespace, visibility, direction, the feature flags, the typing and specialization clauses, multiplicity bounds and its value; expression-valued positions are expression trees. Properties the metamodel does not define live in a separate urn:opensysml:sysml: namespace so a consumer can tell them from the standard vocabulary: memberIndex (declaration order, which the notation is sensitive to and RDF is not), hasBody, the end forms of heads that bind ends, and each element's lines as written, comments included, as sourceText and sourceTail.

XMI input

SysML v1 as UML XMI (OMG XMI 2.5.1, the Eclipse UML2 .uml serialization Papyrus writes, or a .mdzip archive holding it) is migrated to v2 notation by internal/translate/migrate, then takes the notation path. XMI is never written.

RDF back to notation

The structural triples are authoritative. An element is written from its source text while that text still states what the graph states — so comments and layout survive a round trip of an unedited model — and canonically where the two disagree or the graph carries no text, as one from another tool does not. docs/reference/rdf-mapping.md documents the mapping and its limitations.

Index

Constants

View Source
const AnnotationSuffix = "_an"

AnnotationSuffix names the Annotation by which a dependency owns a prefix metadata usage, after the usage it owns, as `_om` names a membership.

View Source
const CompactAPIJSONFormat = "api-json-compact/1"

CompactAPIJSONFormat names the document WriteAPIJSONCompact writes.

View Source
const RootNamespaceSuffix = "_ns"

RootNamespaceSuffix ends the id of the unnamed Namespace that owns a document's top-level elements in the API element form. An encoded id never ends in a lone '_', so the id collides with no element's or membership's.

Variables

This section is empty.

Functions

func APIJSONToSysML added in v0.9.2

func APIJSONToSysML(data []byte, warn func(string)) ([]byte, error)

APIJSONToSysML reads an API element document and converts its owned graph.

func DeclarationNames added in v0.9.2

func DeclarationNames(file *source.SourceFile, root *ast.RootNamespace) (map[source.Span]string, error)

DeclarationNames maps declarations to their RDF qualified names by span. Unnamed declarations use the export's positional `@N` identity.

func DerivedSatellite

func DerivedSatellite(metaclass string) bool

DerivedSatellite reports whether metaclass is one the encoder derives from its side tables rather than a declaration — the materialized relationship elements, a conjugated port definition and its conjugation, a multiplicity range, or the membership relating an expression to its referent. A member element of such a metaclass carries a qualified name and stays addressable.

func Destination

func Destination(path string) (target string, info os.FileInfo, err error)

Destination returns the file a save should write and what is there now, which is nil when nothing is. A symlink resolves to what it points at, so saving over a linked model updates the model instead of unlinking it; a link that resolves to nothing is written where it points.

func IsPositionalIdentity added in v0.9.2

func IsPositionalIdentity(name string) bool

IsPositionalIdentity reports whether a name contains a canonical `@N` segment.

func IsSourceRangeProperty added in v0.9.2

func IsSourceRangeProperty(iri string) bool

IsSourceRangeProperty reports whether iri is one of the four integers that place a declaration in its document: layout, which reading ignores.

func LibraryReference added in v0.9.2

func LibraryReference(graph *rdf.Graph, subject rdf.Term) bool

LibraryReference reports whether subject names a library element the graph references rather than declares: it has no owner or owned relationships.

func MappingElementSubject added in v0.11.0

func MappingElementSubject(graph *rdf.Graph, subject rdf.Term) bool

MappingElementSubject reports whether the subject is emitted as an Element rather than a reified membership edge.

func MappingMembershipEdgeSubject added in v0.11.0

func MappingMembershipEdgeSubject(graph *rdf.Graph, subject rdf.Term) bool

MappingMembershipEdgeSubject reports whether the subject is a membership edge rather than a relationship emitted as its own element.

func MappingMembershipMemberIsElement added in v0.11.0

func MappingMembershipMemberIsElement(graph *rdf.Graph, membership, member rdf.Term) bool

MappingMembershipMemberIsElement reports whether the forward mapping emits a membership's member as an Element rather than as an expression part.

func ModelToRDFWith added in v0.9.2

func ModelToRDFWith(documents []ModelDocument, form IDForm) (*rdf.Graph, error)

ModelToRDFWith converts the documents of one model to a single graph. They are analyzed together, as a workspace analyzes them, and a reference from one document to an element another declares links the subject that document writes for it, as a reference within one document does. Each document's root elements name it (sysx:sourceDocument), since one graph no longer keeps the documents apart. A Referenced document's elements are left out; its declarations' ids are still checked against those the written documents mint.

func NormativeSubject

func NormativeSubject(id, qualifiedName string) bool

NormativeSubject reports whether id is the id the norm fixes for the subject a graph names qualifiedName: the library element the encoder writes under that name, or its owning membership, which names nothing. A user element that carries a library uuid is not the library element, so its id stays its own.

func PositionalIdentities added in v0.9.2

func PositionalIdentities(index *symbols.Index, docs []PositionalDocument, identifies func(*symbols.Symbol) bool) (map[*symbols.Symbol]string, map[string]*symbols.Symbol)

PositionalIdentities maps symbols without qualified identities to export names.

func ReadAPIJSON

func ReadAPIJSON(data []byte) (*rdf.Graph, error)

ReadAPIJSON parses the SysML v2 API's element form — a JSON array of element objects, or a single element object — into the same graph ParseTurtle yields: the "@type" and "@id" of each object and each metamodel key in document order. It is the inverse of WriteAPIJSON, so a graph it builds writes the same elements back; the unnamed root Namespace a document wraps its top-level elements in is dropped, as the Turtle form does not carry it.

func TempStem added in v0.11.0

func TempStem(base string) string

TempStem is base cut to fit a temporary file's name beside it, with a dot, a separator and up to twelve random bytes added, without splitting a UTF-8 sequence.

func ToRDF

func ToRDF(file *source.SourceFile, root *ast.RootNamespace) (*rdf.Graph, error)

ToRDF converts a parsed document into an RDF graph. file must be the source the tree was parsed from: every element and expression carries the notation it was written as alongside its structural triples, so the conversion needs the bytes as well as the tree.

func ToRDFWith

func ToRDFWith(file *source.SourceFile, root *ast.RootNamespace, form IDForm) (*rdf.Graph, error)

ToRDFWith is ToRDF with the id form the caller asks for.

func ToSysML

func ToSysML(graph *rdf.Graph) ([]byte, error)

ToSysML converts an RDF graph back into SysML v2 source text. An element comes back as its sysx:sourceText, byte for byte, while that still states what the graph states, and in canonical notation otherwise.

A subject whose metaclass this mapping does not know, or which lacks the properties needed to rebuild its declaration, is reported as an UnsupportedError: a converted file that dropped an element would be worse than a failed conversion.

func ToSysMLWarn added in v0.9.2

func ToSysMLWarn(graph *rdf.Graph, warn func(string)) ([]byte, error)

ToSysMLWarn converts a graph to notation and reports non-fatal resolutions.

func WriteAPIJSON

func WriteAPIJSON(graph *rdf.Graph) ([]byte, error)

WriteAPIJSON serializes a graph as the SysML v2 API's element form: a JSON array of objects carrying "@type", "@id" and the metamodel properties as keys, with collection values in annotation order.

func WriteAPIJSONCompact added in v0.10.0

func WriteAPIJSONCompact(graph *rdf.Graph, opts CompactAPIJSONOptions) ([]byte, error)

WriteAPIJSONCompact writes the elements WriteAPIJSON writes in a form built to be small: no indentation, each element id written once, and every reference spelled by the position of its id. The document is one object:

{"format":"api-json-compact/1",
 "ids":[<id>, …],               // the id table
 "elementCount":N,              // ids[0..N) are the elements, in order
 "elementIdsAreIds":true,       // present only when elementId is left out (below)
 "referenceKeys":[<key>, …],    // keys whose values are only references or reference arrays
 "elements":[{"@type":…,…}, …]}

Element i has the id ids[i], so it carries no "@id". Under a reference key a reference is the integer index into ids (an array of them for a collection); anywhere else it is {"@id": <index>}. ids beyond elementCount are elements the conversion references but does not write. Unresolved object-property names are null or omitted, as in the element form. When every element's "elementId" is its "@id", as it is unless a document declared another, "elementId" is left out and "elementIdsAreIds" says so: a reader restores it from the table.

func WriteAPIJSONWithOptions added in v0.11.0

func WriteAPIJSONWithOptions(graph *rdf.Graph, options APIJSONOptions) ([]byte, error)

WriteAPIJSONWithOptions writes API JSON and reports unresolved object properties through options.

func WriteFile

func WriteFile(path string, data []byte) (replaced bool, err error)

WriteFile writes a converted model to path, reporting whether it replaced a file that was already there.

A regular file is written atomically: the bytes go to a temporary file in the same directory, are flushed, and are renamed over the destination, so an interrupted write leaves the previous model intact rather than a truncated or empty one. An existing file keeps its permissions, and a symlink is written through rather than replaced.

Anything that is not a regular file — a terminal, a pipe, /dev/null, a process substitution — is written directly, since there is no previous content to protect and replacing it by rename would destroy the pipe or device the user pointed at.

Types

type APIJSONLibraryReference added in v0.12.0

type APIJSONLibraryReference struct {
	ID            string `json:"@id"`
	Type          string `json:"@type"`
	QualifiedName string `json:"qualifiedName"`
}

APIJSONLibraryReference names a standard-library element without declaring a root.

type APIJSONOmission added in v0.11.0

type APIJSONOmission struct {
	Subject   string
	Metaclass string
	Property  string
	Reason    metamodel.Reason
}

APIJSONOmission describes an object-property value omitted because its target could not be resolved.

type APIJSONOptions added in v0.11.0

type APIJSONOptions struct {
	Omitted    func(APIJSONOmission)
	Diagnostic func(string)
	// IncludeLibraryStubs writes ownerless library elements for legacy readers.
	IncludeLibraryStubs bool
	// LibraryReferences receives the names of referenced standard-library elements.
	LibraryReferences func([]APIJSONLibraryReference)
}

APIJSONOptions configures diagnostics collected while writing API JSON.

type APIJSONReadError added in v0.9.2

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

APIJSONReadError reports a failure to parse an API element document.

func (*APIJSONReadError) Error added in v0.9.2

func (e *APIJSONReadError) Error() string

func (*APIJSONReadError) Unwrap added in v0.9.2

func (e *APIJSONReadError) Unwrap() error

type CompactAPIJSONOptions added in v0.10.0

type CompactAPIJSONOptions struct {
	// OmitDerived leaves out every property the metamodel derives, except the
	// ones named in KeepDerived. A derived property restates what the owned
	// properties already say, so a reader that follows ownership, typing and
	// specialization does not need it.
	OmitDerived bool
	// KeepDerived names the derived properties still written when OmitDerived is set.
	KeepDerived         []string
	Omitted             func(APIJSONOmission)
	Diagnostic          func(string)
	IncludeLibraryStubs bool
	LibraryReferences   func([]APIJSONLibraryReference)
}

CompactAPIJSONOptions chooses what the compact form leaves out.

type ElementIDDocument added in v0.12.0

type ElementIDDocument struct {
	File       *source.SourceFile
	Root       *ast.RootNamespace
	ParseDiags []parser.Diagnostic
}

ElementIDDocument is a document whose elementIds are read: its parse and the parse's errors; one given by its text alone is parsed for the conversion.

type ElementIDReader added in v0.12.0

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

ElementIDReader reads the elementId Convert writes for each element of a model, from one conversion of the model made on first use. A model Convert refuses has no ids: the refusal is kept and every read reports it.

func NewElementIDReader added in v0.12.0

func NewElementIDReader(documents []ElementIDDocument) *ElementIDReader

NewElementIDReader reads the elementIds of the model documents make; a document without text is not written. Nothing is converted until Read.

func (*ElementIDReader) Read added in v0.12.0

func (r *ElementIDReader) Read(doc string, decl ast.Node, fqn string) (string, error)

Read is the elementId written for the element declared at decl in document doc, named fqn (ElementIDs.OfDeclaration), or why the model has none.

func (*ElementIDReader) ReadExpressionPart added in v0.12.0

func (r *ElementIDReader) ReadExpressionPart(doc string, node ast.Node, slot string) (element, membership string, err error)

ReadOwningMembership is the elementId of the owning membership of the element declared at decl in doc, named fqn; empty where the conversion writes none. ReadExpressionPart reads the ids of the parameter at slot of the expression written at node, and of the membership that owns it.

func (*ElementIDReader) ReadOwningMembership added in v0.12.0

func (r *ElementIDReader) ReadOwningMembership(doc string, decl ast.Node, fqn string) (string, error)

func (*ElementIDReader) ReadRelationship added in v0.12.0

func (r *ElementIDReader) ReadRelationship(doc string, node ast.Node) (string, error)

ReadRelationship is the elementId of the relationship element the notation implies at node in doc — a head clause's, a bound end's reference subsetting, a dependency's prefix-metadata annotation; empty where the conversion writes none.

type ElementIDs added in v0.9.2

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

ElementIDs reports the elementId a conversion of a model writes for each of its elements, in the qualified id form, from the identity tables Convert mints them from (ToRDF's for one document, ModelToRDFWith's for several), so a library file's copy, a declared id and scope qualification come out as written.

func NewElementIDs added in v0.9.2

func NewElementIDs(documents []ModelDocument) (*ElementIDs, error)

NewElementIDs records the elementId Convert writes for each element of the documents' model from the identity tables the ids are minted from — nothing is written — refusing what the declarations' identity claims refuse in Convert: ids colliding within a document (mintDeclarations) or across documents.

func (*ElementIDs) Of added in v0.9.2

func (ids *ElementIDs) Of(fqn string) (string, bool)

Of is the elementId written for the element named fqn: the model's own as the conversion wrote it, or, for a standard library element the model does not declare, the normative id every reference to it carries. False where the conversion writes none, as for a library element a model annotates with an id of its own, whose references are written by name.

func (*ElementIDs) OfDeclaration added in v0.9.2

func (ids *ElementIDs) OfDeclaration(doc string, decl ast.Node, fqn string) (string, bool)

func (*ElementIDs) OfExpressionPart added in v0.12.0

func (ids *ElementIDs) OfExpressionPart(doc string, node ast.Node, slot string) (element, membership string, ok bool)

OfDeclaration is the elementId written for the element declared at decl in document doc, named fqn: the node's own, its span's in a reparse, else Of(fqn). OfExpressionPart is the id written for the parameter at slot of the expression written at node (`in0`… for its operands and type argument, `out` for its result), and of the membership that owns it.

func (*ElementIDs) OwningMembershipOfDeclaration added in v0.12.0

func (ids *ElementIDs) OwningMembershipOfDeclaration(doc string, decl ast.Node, fqn string) (string, bool)

OwningMembershipOfDeclaration is the elementId written for the owning membership of the element declared at decl in doc, named fqn; false for a root or an unknown element.

func (*ElementIDs) RelationshipOf added in v0.12.0

func (ids *ElementIDs) RelationshipOf(doc string, node ast.Node) (string, bool)

RelationshipOf is the elementId written for the relationship element the notation implies at node in document doc (writtenRelationships); false where none is written.

type IDForm

type IDForm int

IDForm is how the encoder spells the derived ids of elements, memberships and expression nodes that no ElementId annotation declares.

const (
	// IDQualifiedName derives each id from the element's qualified name, so an
	// id reads where its element sits in the model. The default.
	IDQualifiedName IDForm = iota
	// IDUUID derives each id as a name-based uuid the way the SysML v2 library
	// convention does: the model's package namespace is
	// uuid5(NamespaceURL, elementIRI(root)), and every derived id under it is
	// uuid5(pkg, the qualified-name-derived local id it otherwise carries).
	IDUUID
)

func ParseIDForm

func ParseIDForm(s string) (IDForm, bool)

ParseIDForm reads the -id flag's argument.

type ModelDocument added in v0.9.2

type ModelDocument struct {
	File *source.SourceFile
	Root *ast.RootNamespace
	// Referenced is a document analyzed with the model but not written: a
	// reference into it links the id its element is written under on its own.
	Referenced bool
}

ModelDocument is one parsed document of a model converted as a whole.

type PositionalDocument added in v0.9.2

type PositionalDocument struct {
	File *source.SourceFile
	Root *symbols.Scope
}

PositionalDocument pairs a source file with the scope containing its symbols.

type Staged added in v0.9.2

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

Staged is a file written beside its destination but not yet renamed over it, so a set of files can be committed together or discarded.

func Stage added in v0.9.2

func Stage(path string, data []byte) (*Staged, error)

Stage writes data to a temporary file beside path, ready to Commit; path must be absent or a regular file, as there is nothing else to rename over.

func (*Staged) Commit added in v0.9.2

func (s *Staged) Commit() error

Commit renames the staged file over its destination.

func (*Staged) Discard added in v0.9.2

func (s *Staged) Discard()

Discard removes the staged file, leaving its destination as it was.

type UnsupportedError

type UnsupportedError struct {
	What string
	Note string
}

UnsupportedError reports a construct the conversion cannot represent. It names the element so the user can find it, rather than converting a model that silently lost part of itself.

func (*UnsupportedError) Error

func (e *UnsupportedError) Error() string

Jump to

Keyboard shortcuts

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