diff --git a/runtime/sema/check_reference_expression.go b/runtime/sema/check_reference_expression.go index 8ae9906317..68d8c20e72 100644 --- a/runtime/sema/check_reference_expression.go +++ b/runtime/sema/check_reference_expression.go @@ -92,7 +92,9 @@ func (checker *Checker) VisitReferenceExpression(referenceExpression *ast.Refere // If the reference type was a non-optional type, // check that the referenced expression does not have an optional type - if _, ok := actualType.(*OptionalType); ok != isOpt { + // Do not report an error if the `expectedLeftType` is unknown + + if _, ok := actualType.(*OptionalType); ok != isOpt && expectedLeftType != nil { checker.report(&TypeMismatchError{ ExpectedType: expectedLeftType, ActualType: actualType, diff --git a/runtime/tests/checker/reference_test.go b/runtime/tests/checker/reference_test.go index 4b4fb18632..0c328a1a1f 100644 --- a/runtime/tests/checker/reference_test.go +++ b/runtime/tests/checker/reference_test.go @@ -1304,3 +1304,40 @@ func TestCheckReferenceTypeImplicitConformance(t *testing.T) { require.IsType(t, &sema.TypeMismatchError{}, errs[0]) }) } + +func TestCheckReferenceCreationWithInvalidType(t *testing.T) { + + t.Parallel() + + t.Run("invalid reference type", func(t *testing.T) { + + t.Parallel() + + _, err := ParseAndCheck(t, ` + let foo: AnyStruct? = nil + let x = &foo as &Foo + `) + + errs := RequireCheckerErrors(t, err, 1) + + var notDeclaredError *sema.NotDeclaredError + require.ErrorAs(t, errs[0], ¬DeclaredError) + }) + + t.Run("valid non-reference type", func(t *testing.T) { + + t.Parallel() + + _, err := ParseAndCheck(t, ` + struct Foo {} + + let foo: AnyStruct? = nil + let x = &foo as Foo + `) + + errs := RequireCheckerErrors(t, err, 1) + + var nonReferenceTypeReferenceError *sema.NonReferenceTypeReferenceError + require.ErrorAs(t, errs[0], &nonReferenceTypeReferenceError) + }) +}