Skip to content

Commit

Permalink
Merge pull request #3422 from onflow/supun/port-239
Browse files Browse the repository at this point in the history
  • Loading branch information
turbolent authored Jun 13, 2024
2 parents 3d85cea + 20e98d9 commit fbb756e
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 32 deletions.
27 changes: 1 addition & 26 deletions runtime/sema/check_binary_expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -441,13 +441,6 @@ func (checker *Checker) checkBinaryExpressionNilCoalescing(
return InvalidType
}

leftInner := leftOptional.Type

if leftInner == NeverType {
return rightType
}
canNarrow := false

if !rightIsInvalid {

if rightType.IsResourceType() {
Expand All @@ -458,25 +451,7 @@ func (checker *Checker) checkBinaryExpressionNilCoalescing(
},
)
}

if !IsSubType(rightType, leftOptional) {

checker.report(
&InvalidBinaryOperandError{
Operation: operation,
Side: common.OperandSideRight,
ExpectedType: leftOptional,
ActualType: rightType,
Range: ast.NewRangeFromPositioned(checker.memoryGauge, expression.Right),
},
)
} else {
canNarrow = IsSubType(rightType, leftInner)
}
}

if !canNarrow {
return leftOptional
}
return leftInner
return LeastCommonSuperType(leftOptional.Type, rightType)
}
27 changes: 21 additions & 6 deletions runtime/tests/checker/nil_coalescing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,29 @@ func TestCheckInvalidNilCoalescingNonMatchingTypes(t *testing.T) {

t.Parallel()

_, err := ParseAndCheck(t, `
let x: Int? = 1
let y = x ?? false
`)
t.Run("with super type", func(t *testing.T) {
t.Parallel()

errs := RequireCheckerErrors(t, err, 1)
_, err := ParseAndCheck(t, `
let x: Int? = 1
let y = x ?? false
`)

require.NoError(t, err)
})

t.Run("no super type", func(t *testing.T) {

t.Parallel()

_, err := ParseAndCheck(t, `
let x: Int? = 1
let y: Int = x ?? false
`)

assert.IsType(t, &sema.InvalidBinaryOperandError{}, errs[0])
errs := RequireCheckerErrors(t, err, 1)
assert.IsType(t, &sema.TypeMismatchError{}, errs[0])
})
}

func TestCheckNilCoalescingAny(t *testing.T) {
Expand Down
18 changes: 18 additions & 0 deletions runtime/tests/checker/resources_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9936,3 +9936,21 @@ func TestCheckInvalidNestedResourceCapture(t *testing.T) {
require.NoError(t, err)
})
}

func TestCheckInvalidOptionalResourceCoalescingRightSideNilLeftSide(t *testing.T) {
t.Parallel()

_, err := ParseAndCheck(t, `
resource R {}
fun test() {
let rs: @[R?] <- [nil, nil]
rs[0] <-! create R()
rs[1] <-! nil ?? rs[0]
destroy rs
}
`)

errs := RequireCheckerErrors(t, err, 1)

assert.IsType(t, &sema.InvalidNilCoalescingRightResourceOperandError{}, errs[0])
}

0 comments on commit fbb756e

Please sign in to comment.