There are two ways to cast a node to a concept in MPS:
someNode : MyConcept or
someNode as MyConcept. The
variant is strict: if
someNode is not an instance of
MyConcept, an exception will be thrown. The
null in this case.
You should almost never use the strict
: variant. You may think you have it under control and know what node you are
getting, but MPS occasionally puts nodes in unexpected contexts due to the way it works.
For example, you might assume that if you have defined
Parent concept to have a child
children : Child[0..n], all
its children will always be subconcepts of
Children. Except that due to some generator rules a
Child might get
reduced to a Java
Statement while its parent remains a
Or you might have a type inference rule that gives your nodes a particular type and so you cast
someNode.type to a
particular type. But then something goes wrong during a migration and a subexpression goes missing and now
someNode.type is a
You might assume that since concept
Child is not marked as “rootable” and is only mentioned as a child of
child.parent is going to always be a
Parent. But then somebody puts a
Child into a generator template or a
unit test and suddenly its parent is a reduction rule or a test node container.
These unexpected uses do not happen very often and may be easy to shrug off. Once they happen however, they cause the
red blinking exclamation mark to appear, making your tool look unprofessional. At the same time, you can avoid this
simply by switching to using
as casts by default. Since the SModel language used to manipulate nodes is null-safe,
your code will often not even need to change much.
When should you still use the strict
: cast? I can think of several cases. Generator errors caused by invalid
assumptions are easier to debug if the generator fails early rather than produces incorrect code, so make it strict.
Likewise, you also want your tests to be strict rather than resilient. And finally, if you write one-off code such
as experimenting with MPS Console, you might want your code to be strict to help you validate your assumptions.