Re-resolve a model after building

New in v1.1.0 Labs

After you change a model with the Builder API, part of the model is out of date until you call resolve(). Read this page to learn which part is out of date, what resolve() updates, and what it reports when a change makes the model invalid. Run the example in Builder API before you read this page.

What a constructor writes, and what it does not

A model has two layers. The first layer is what is written: the elements, their names, and relationships such as : Wheel or :> Vehicle. The second layer is what Syside derives from the first layer when it loads a model:

  • Resolved names. In part wheel : Wheel;, the relationship from wheel to the definition Wheel exists only after the name Wheel is resolved.

  • Implied relationships. The SysML v2 specification requires relationships that are not written. For example, every part def specializes Parts::Part from the standard library, and a part inside a definition subsets subparts. Your elements get the features of the standard library through these relationships.

  • Validation. Syside checks rules such as “a part is typed only by part or item definitions”, and reports the rules that are broken.

The constructors and the set_, add_ and remove_ functions change only the first layer. The second layer is not changed after loading until resolve() is run. resolve() derives the second layer again for every document in the model. It returns errors and warnings as a Diagnostics object, the same type that loading returns.

Seeing the difference

The script below makes three changes to a small model. For each change, the script prints the model’s state before and after resolve():

import syside
from syside import query
from syside.experimental import builder

MODEL = """
package Rover {
    attribute def Mass;
    part def Chassis {
        part engine : Engine;
    }
}
"""


def errors(diagnostics: syside.Diagnostics) -> list[str]:
    """Return each error as ``code: message``."""
    return [f"{error.code}: {error.message}" for _, error in diagnostics.errors]


def supertypes(element: syside.Type) -> list[str]:
    """Return the qualified names of what ``element`` specializes."""
    return [
        str(supertype.qualified_name) for supertype in element.heritage.elements
    ]


def main() -> None:
    model = syside.try_load_model([("memory://rover.sysml", MODEL)])
    print("As loaded:", errors(model.diagnostics))

    rover = query.find_by_qualified_name(model, "Rover")
    chassis = query.find_by_qualified_name(model, "Rover::Chassis")
    assert isinstance(rover, syside.Package)
    assert isinstance(chassis, syside.PartDefinition)

    # 1. The typing relationship to Engine exists only after resolve()
    builder.new_part_def(rover, "Engine")
    engine = query.find_by_qualified_name(model, "Rover::Chassis::engine")
    assert isinstance(engine, syside.PartUsage)
    print("Engine typed before resolve:", supertypes(engine))
    print("After resolve:", errors(builder.resolve(model)))
    print("Engine typed after resolve:", supertypes(engine))

    # 2. Implied relationships exist only after resolve()
    wheel = builder.new_part(chassis, "wheel")
    print("Wheel specializes before resolve:", supertypes(wheel))
    builder.resolve(model)
    print("Wheel specializes after resolve:", supertypes(wheel))

    # 3. A part typed by an attribute def is invalid, but the builder allows it
    mass = query.find_by_qualified_name(model, "Rover::Mass")
    assert isinstance(mass, syside.AttributeDefinition)
    builder.new_part(chassis, "ballast", defined_by=[mass])
    diagnostics = builder.resolve(model)
    print("After typing a part by an attribute def:", errors(diagnostics))
    try:
        # If there are errors, stop the script, as load_model does
        if diagnostics.contains_errors():
            raise syside.ModelError(model.unlock(), diagnostics)
    except syside.ModelError:
        print("ModelError raised")


if __name__ == "__main__":
    main()

The output is:

As loaded: ['item-usage-types: An item usage must only be defined by item definitions or KerML structures', "reference-error: No Type named 'Engine' found."]
Engine typed before resolve: ["'<placeholder Classifier>'", 'Items::Item::subparts']
After resolve: []
Engine typed after resolve: ['Rover::Engine', 'Items::Item::subparts']
Wheel specializes before resolve: []
Wheel specializes after resolve: ['Items::Item::subparts']
After typing a part by an attribute def: ['item-usage-types: An item usage must only be defined by item definitions or KerML structures']
ModelError raised

A definition created after loading. The model has part engine : Engine; but no Engine, so loading reports No Type named 'Engine' found. The script then creates Engine with the builder. The typing relationship from engine to Engine does not exist until resolve() is run. After that, both errors are gone. Imports work the same way: if you add an import with the builder, references to the imported names are not resolved until resolve() is run.

An implied relationship. The script creates the part wheel. The implied subsetting relationship from wheel to Items::Item::subparts does not exist until resolve() is run. Until then, functions that use inherited features or specialization, such as specializes(), do not see that relationship.

An invalid model. The script types the part ballast by the attribute definition Mass. The builder allows this, because part ballast : Mass; is correct textual syntax, and the builder checks only syntax. The SysML v2 rule that a part must be typed by part or item definitions is not checked until resolve() is run. Then resolve() reports an item-usage-types error. If there are errors, the script stops by raising ModelError. This is what load_model() does for a file with errors.

When to call resolve()

Call resolve() once after a group of changes. Call it before you use the second layer, for example before you evaluate expressions or call query functions that use specialization or inherited members. You can call resolve() after every change, but each call derives the second layer again for every document in the model, which takes time.

Check the diagnostics that resolve() returns. If you do not, your script can save a model that syside check reports errors in.