Skip to content

Commit

Permalink
Merge pull request #2687 from onflow/supun/fix-type-error
Browse files Browse the repository at this point in the history
Fix error on reference creation with invalid type
  • Loading branch information
SupunS authored Aug 2, 2023
2 parents 7655a90 + 13d2513 commit c8833d2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
4 changes: 3 additions & 1 deletion runtime/sema/check_reference_expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
37 changes: 37 additions & 0 deletions runtime/tests/checker/reference_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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], &notDeclaredError)
})

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)
})
}

0 comments on commit c8833d2

Please sign in to comment.