Skip to content

Commit ebeb870

Browse files
committed
[ast] Add wrapInOptionalType to CanType and TypeBase.
This API just wraps the current type T into an Optional<T> and returns the Optional<T> type. We use this all the time in the optimizer and I found I needed it in SILGen as well but at the AST level, hence the addition. In the next commit, I change the API in SILType that does this to use this helper instead. I am doing that to make it easier to cherry-pick this with a subsequent change I am making to fix a bug.
1 parent e1412a0 commit ebeb870

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

include/swift/AST/Type.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,7 @@ class CanType : public Type {
419419
static bool isObjCExistentialTypeImpl(CanType type);
420420
static bool isTypeErasedGenericClassTypeImpl(CanType type);
421421
static CanType getOptionalObjectTypeImpl(CanType type);
422+
static CanType wrapInOptionalTypeImpl(CanType type);
422423
static CanType getReferenceStorageReferentImpl(CanType type);
423424
static CanType getWithoutSpecifierTypeImpl(CanType type);
424425

@@ -523,6 +524,13 @@ class CanType : public Type {
523524

524525
bool isForeignReferenceType(); // in Types.h
525526

527+
/// Return this type wrapped into an Optional type. E.x.: 'T' ->
528+
/// 'Optional<T>'.
529+
CanType wrapInOptionalType() const {
530+
return wrapInOptionalTypeImpl(*this);
531+
}
532+
533+
/// If this is a type Optional<T>, return T. Otherwise return CanType().
526534
CanType getOptionalObjectType() const {
527535
return getOptionalObjectTypeImpl(*this);
528536
}

include/swift/AST/Types.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1232,6 +1232,9 @@ class alignas(1 << TypeAlignInBits) TypeBase
12321232
const ValueDecl *derivedDecl,
12331233
Type memberType);
12341234

1235+
/// If this type is T, return Optional<T>.
1236+
Type wrapInOptionalType() const;
1237+
12351238
/// Return T if this type is Optional<T>; otherwise, return the null type.
12361239
Type getOptionalObjectType();
12371240

lib/AST/Type.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -798,6 +798,17 @@ CanType CanType::getOptionalObjectTypeImpl(CanType type) {
798798
return CanType();
799799
}
800800

801+
Type TypeBase::wrapInOptionalType() const {
802+
auto &ctx = getASTContext();
803+
auto *result = BoundGenericEnumType::get(ctx.getOptionalDecl(), Type(),
804+
{ getCanonicalType() });
805+
return result;
806+
}
807+
808+
CanType CanType::wrapInOptionalTypeImpl(CanType type) {
809+
return type->wrapInOptionalType()->getCanonicalType();
810+
}
811+
801812
Type TypeBase::getAnyPointerElementType(PointerTypeKind &PTK) {
802813
auto &C = getASTContext();
803814
if (isUnsafeMutableRawPointer()) {

0 commit comments

Comments
 (0)