shared: add a shared Either type

This commit is contained in:
erik-krogh
2022-11-30 16:35:39 +01:00
parent 073e9bc52f
commit 50a91b5017

View File

@@ -0,0 +1,40 @@
/** Provides a module for constructing a union `Either` type. */
/** A type with `toString`. */
signature class TypeWithToString {
string toString();
}
/**
* Constructs an `Either` type that is a disjoint union of two types.
*/
module Either<TypeWithToString Left, TypeWithToString Right> {
private newtype TEither =
TLeft(Left c) or
TRight(Right c)
/**
* An either type. This is either a `Left` or a `Right` wrapping the given
* type.
*/
class Either extends TEither {
/** Gets a textual representation of this element. */
string toString() {
exists(Left c | this = TLeft(c) and result = c.toString())
or
exists(Right c | this = TRight(c) and result = c.toString())
}
/** Gets the element, if this is a `Left`. */
Left asLeft() { this = TLeft(result) }
/** Gets the element, if this is a `Right`. */
Right asRight() { this = TRight(result) }
}
/** Makes an `Either` from an instanceof of `Left` */
Left left(Left c) { result = c }
/** Makes an `Either` from an instanceof of `Right` */
Right right(Right c) { result = c }
}