Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce dereference on the Reference type #2945

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions runtime/interpreter/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -20311,6 +20311,17 @@ func (v *EphemeralReferenceValue) GetMember(
) Value {
self := v.MustReferencedValue(interpreter, locationRange)

switch name {
case sema.ReferenceTypeDereferenceFunctionName:
return NewHostFunctionValue(
interpreter,
sema.ReferenceDereferenceFunctionType(v.BorrowedType),
func(invocation Invocation) Value {
return v.Value
},
Copy link
Contributor Author

@darkdrag00nv2 darkdrag00nv2 Nov 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation of dereference on EphemeralReferenceValue looks straightforward. Is this correct or am I missing something?

Copy link
Contributor

@bluesign bluesign Nov 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this create new Value (copy of the value somehow ) ? something like Transfer etc.

This comment was marked as outdated.

Copy link
Contributor

@bluesign bluesign Nov 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking more like:

let x: &[Int] = &[1]
x.dereference().append(2)

PS: if we make a copy also we can support non-primitives like structs

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this needs a Transfer to the stack, i.e.

.Transfer(
	interpreter,
	locationRange,
	atree.Address{},
	false,
	nil,
	nil,
)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great point @bluesign to test by operating on the returned value directly, my example above, let ints2 = ref.dereference() was adding a copy 👍

)
}

return interpreter.getMember(self, locationRange, name)
}

Expand Down
71 changes: 65 additions & 6 deletions runtime/sema/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -5957,8 +5957,10 @@

// ReferenceType represents the reference to a value
type ReferenceType struct {
Type Type
Authorization Access
Type Type
Authorization Access
memberResolvers map[string]MemberResolver
memberResolversOnce sync.Once
}

var _ Type = &ReferenceType{}
Expand Down Expand Up @@ -6113,10 +6115,6 @@
return f(NewReferenceType(gauge, t.Authorization, mappedType))
}

func (t *ReferenceType) GetMembers() map[string]MemberResolver {
return t.Type.GetMembers()
}

func (t *ReferenceType) isValueIndexableType() bool {
referencedType, ok := t.Type.(ValueIndexableType)
if !ok {
Expand Down Expand Up @@ -6219,6 +6217,67 @@
}
}

func (t *ReferenceType) GetMembers() map[string]MemberResolver {
t.initializeMemberResolvers()
return t.memberResolvers
}

const ReferenceTypeDereferenceFunctionName = "dereference"

const referenceTypeDereferenceFunctionDocString = `
todo
`

func (t *ReferenceType) initializeMemberResolvers() {
t.memberResolversOnce.Do(func() {
resolvers := t.Type.GetMembers()

// Add members applicable to all ReferenceType instances
members := map[string]MemberResolver{
ReferenceTypeDereferenceFunctionName: {
Kind: common.DeclarationKindFunction,
Resolve: func(memoryGauge common.MemoryGauge, identifier string, targetRange ast.Range, report func(error)) *Member {
innerType := t.Type

// TODO: Define a new error type.
if innerType.IsResourceType() {
report(
&InvalidResourceArrayMemberError{
Name: identifier,
DeclarationKind: common.DeclarationKindFunction,
Range: targetRange,
},
)
}

return NewPublicFunctionMember(
memoryGauge,
t,
identifier,
ReferenceDereferenceFunctionType(t.Type),
referenceTypeDereferenceFunctionDocString,
)
},
},
}

// TODO: What if the inner type also has a function with the name "dereference"?
for key, member := range members {

Check failure on line 6265 in runtime/sema/type.go

View workflow job for this annotation

GitHub Actions / Lint

range statement over map: map[string]github.com/onflow/cadence/runtime/sema.MemberResolver (maprange)

Check failure on line 6265 in runtime/sema/type.go

View workflow job for this annotation

GitHub Actions / Lint

range statement over map: map[string]github.com/onflow/cadence/runtime/sema.MemberResolver (maprange)
resolvers[key] = member
}

t.memberResolvers = resolvers
})
}

func ReferenceDereferenceFunctionType(borrowedType Type) *FunctionType {
return &FunctionType{
ReturnTypeAnnotation: NewTypeAnnotation(borrowedType),
// TODO: Confirm that this can be called View.
Purity: FunctionPurityView,
}
}

const AddressTypeName = "Address"

// AddressType represents the address type
Expand Down
121 changes: 121 additions & 0 deletions runtime/tests/checker/reference_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3061,3 +3061,124 @@ func TestCheckResourceReferenceIndexNilAssignment(t *testing.T) {
require.IsType(t, &sema.InvalidResourceAssignmentError{}, errors[2])
})
}

func TestCheckReferenceDereferenceFunction(t *testing.T) {

t.Parallel()

t.Run("variable declaration type annotation", func(t *testing.T) {

t.Parallel()

t.Run("non-auth", func(t *testing.T) {

t.Parallel()

checker, err := ParseAndCheck(t, `
let x: &Int = &1
let y: Int = x.dereference()
`)

require.NoError(t, err)

yType := RequireGlobalValue(t, checker.Elaboration, "y")

assert.Equal(t,
sema.IntType,
yType,
)
})

// t.Run("auth", func(t *testing.T) {

// t.Parallel()

// _, err := ParseAndCheck(t, `
// entitlement X
// let x: auth(X) &Int = &1
// `)

// require.NoError(t, err)
// })

// t.Run("non-reference type", func(t *testing.T) {

// t.Parallel()

// _, err := ParseAndCheck(t, `
// let x: Int = &1
// `)

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

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

// t.Run("variable declaration type annotation", func(t *testing.T) {

// t.Run("non-auth", func(t *testing.T) {

// t.Parallel()

// _, err := ParseAndCheck(t, `
// let x = &1 as &Int
// `)

// require.NoError(t, err)
// })

// t.Run("auth", func(t *testing.T) {

// t.Parallel()

// _, err := ParseAndCheck(t, `
// entitlement X
// let x = &1 as auth(X) &Int
// `)

// require.NoError(t, err)
// })

// t.Run("non-reference type", func(t *testing.T) {

// t.Parallel()

// _, err := ParseAndCheck(t, `
// let x = &1 as Int
// `)

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

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

// t.Run("invalid non-auth to auth cast", func(t *testing.T) {

// t.Parallel()

// _, err := ParseAndCheck(t, `
// entitlement X
// let x = &1 as &Int as auth(X) &Int
// `)

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

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

// t.Run("missing type", func(t *testing.T) {

// t.Parallel()

// _, err := ParseAndCheck(t, `
// let x = &1
// `)

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

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

}
25 changes: 25 additions & 0 deletions runtime/tests/interpreter/reference_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1719,3 +1719,28 @@ func TestInterpretInvalidatedReferenceToOptional(t *testing.T) {
_, err := inter.Invoke("main")
require.NoError(t, err)
}

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

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

inter := parseCheckAndInterpret(t, `
fun main(): Int {
let x: &Int = &1
return x.dereference()
}
`)

value, err := inter.Invoke("main")
require.NoError(t, err)

AssertValuesEqual(
t,
inter,
interpreter.NewIntValueFromInt64(nil, 1),
value,
)
})
}
Loading