mirror of
https://github.com/github/codeql.git
synced 2026-04-29 02:35:15 +02:00
shared: add a shared Either type
This commit is contained in:
40
shared/util/codeql/util/Either.qll
Normal file
40
shared/util/codeql/util/Either.qll
Normal 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 }
|
||||
}
|
||||
Reference in New Issue
Block a user