From 13d25132ee67be2fa4c6bfe0970a96eb8d36680a Mon Sep 17 00:00:00 2001 From: Supun Setunga Date: Wed, 2 Aug 2023 09:48:11 -0700 Subject: [PATCH] Fix error on reference creation with invalid type --- runtime/sema/check_reference_expression.go | 4 ++- runtime/tests/checker/reference_test.go | 37 ++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) 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) + }) +}