Skip to content

Commit

Permalink
Merge pull request #2835 from onflow/sainati/view-before
Browse files Browse the repository at this point in the history
Check `before` statements in `view` contexts
  • Loading branch information
dsainati1 authored Oct 3, 2023
2 parents 09fb4b8 + bf4207b commit 445adf4
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 3 deletions.
5 changes: 4 additions & 1 deletion runtime/sema/check_function.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,10 @@ func (checker *Checker) visitWithPostConditions(postConditions *ast.Conditions,

checker.Elaboration.SetPostConditionsRewrite(postConditions, rewriteResult)

checker.visitStatements(rewriteResult.BeforeStatements)
// all condition blocks are `view`
checker.InNewPurityScope(true, func() {
checker.visitStatements(rewriteResult.BeforeStatements)
})
}

body()
Expand Down
89 changes: 89 additions & 0 deletions runtime/tests/checker/conditions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1018,3 +1018,92 @@ func TestCheckRewrittenPostConditions(t *testing.T) {

})
}

func TestCheckBeforeConditions(t *testing.T) {

t.Parallel()

t.Run("function call", func(t *testing.T) {

t.Parallel()

_, err := ParseAndCheck(t, `
fun impure(): Int {
return 0
}
fun test() {
post {
before(impure()) > 0
}
}
`)

errs := RequireCheckerErrors(t, err, 1)

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

t.Run("view function call", func(t *testing.T) {

t.Parallel()

_, err := ParseAndCheck(t, `
view fun pure(): Int {
return 0
}
fun test() {
post {
before(pure()) > 0
}
}
`)

require.NoError(t, err)
})

t.Run("nested function call", func(t *testing.T) {

t.Parallel()

_, err := ParseAndCheck(t, `
view fun pure(): Int {
return 0
}
fun impure(): Int {
return 0
}
fun test() {
post {
before(before(impure())) > pure()
}
}
`)

errs := RequireCheckerErrors(t, err, 1)

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

t.Run("nested pure function call", func(t *testing.T) {

t.Parallel()

_, err := ParseAndCheck(t, `
view fun pure(): Int {
return 0
}
fun test() {
post {
before(before(pure())) > 0
}
}
`)

require.NoError(t, err)
})
}
5 changes: 3 additions & 2 deletions runtime/tests/checker/resources_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5673,9 +5673,10 @@ func TestCheckInvalidationInPostConditionBefore(t *testing.T) {
}
`)

errs := RequireCheckerErrors(t, err, 1)
errs := RequireCheckerErrors(t, err, 2)

assert.IsType(t, &sema.ResourceUseAfterInvalidationError{}, errs[0])
assert.IsType(t, &sema.PurityError{}, errs[0])
assert.IsType(t, &sema.ResourceUseAfterInvalidationError{}, errs[1])
}

func TestCheckInvalidationInPostCondition(t *testing.T) {
Expand Down

0 comments on commit 445adf4

Please sign in to comment.