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 StructStringer #3594

Merged
merged 17 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
4 changes: 4 additions & 0 deletions runtime/interpreter/interpreter.go
Original file line number Diff line number Diff line change
Expand Up @@ -4866,6 +4866,10 @@ func (interpreter *Interpreter) GetInterfaceType(
typeID TypeID,
) (*sema.InterfaceType, error) {
if location == nil {
var interfaceType = sema.NativeInterfaceTypes[qualifiedIdentifier]
if interfaceType != nil {
return interfaceType, nil
}
return nil, InterfaceMissingLocationError{
QualifiedIdentifier: qualifiedIdentifier,
}
Expand Down
59 changes: 59 additions & 0 deletions runtime/sema/stringer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Cadence - The resource-oriented smart contract programming language
*
* Copyright Flow Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package sema

import (
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/common"
)

const StringerTypeName = "Stringer"
turbolent marked this conversation as resolved.
Show resolved Hide resolved

var StringerType = func() *InterfaceType {
SupunS marked this conversation as resolved.
Show resolved Hide resolved

stringerType := &InterfaceType{
Identifier: StringerTypeName,
CompositeKind: common.CompositeKindStructure,
Members: &StringMemberOrderedMap{},
}

const StringerTypeToStringFunctionDocString = `Returns this object as a String.`

const StringerTypeToStringFunctionName = "toString"

var StringerTypeToStringFunctionType = &FunctionType{
Purity: FunctionPurityView,
ReturnTypeAnnotation: NewTypeAnnotation(
StringType,
),
}

var members = []*Member{
NewUnmeteredFunctionMember(
stringerType,
PrimitiveAccess(ast.AccessAll),
StringerTypeToStringFunctionName,
StringerTypeToStringFunctionType,
StringerTypeToStringFunctionDocString,
),
}

stringerType.Members = MembersAsMap(members)
return stringerType
}()
49 changes: 49 additions & 0 deletions runtime/sema/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -4198,6 +4198,7 @@ func init() {
DeploymentResultType,
HashableStructType,
&InclusiveRangeType{},
StringerType,
},
)

Expand Down Expand Up @@ -4899,6 +4900,17 @@ func IsHashableStructType(t Type) bool {
}
}

// which simple types conform to stringer interface (except Bool?)
turbolent marked this conversation as resolved.
Show resolved Hide resolved
func IsStringerType(t Type) bool {
switch t {
case BoolType, CharacterType, StringType:
return true
default:
return IsSubType(t, NumberType) ||
IsSubType(t, PathType) || IsSubType(t, TheAddressType)
}
}

func (t *CompositeType) GetBaseType() Type {
return t.baseType
}
Expand Down Expand Up @@ -7825,6 +7837,12 @@ func checkSubTypeWithoutEquality(subType Type, superType Type) bool {
IsSubsetOf(typedSubType.EffectiveInterfaceConformanceSet())
}

// STRINGERTODO: other options? how to make existing simple types
// conform to an intersection type?
turbolent marked this conversation as resolved.
Show resolved Hide resolved
if typedSuperType.Types[0].Identifier == StringerTypeName {
return IsStringerType(subType)
}

SupunS marked this conversation as resolved.
Show resolved Hide resolved
default:
// Supertype (intersection) has a non-Any* legacy type

Expand Down Expand Up @@ -9534,3 +9552,34 @@ func init() {
})
}
}

var NativeInterfaceTypes = map[string]*InterfaceType{}

func init() {
interfaceTypes := []*InterfaceType{
StringerType,
}

for len(interfaceTypes) > 0 {
lastIndex := len(interfaceTypes) - 1
interfaceType := interfaceTypes[lastIndex]
interfaceTypes[lastIndex] = nil
interfaceTypes = interfaceTypes[:lastIndex]

NativeInterfaceTypes[interfaceType.QualifiedIdentifier()] = interfaceType

nestedTypes := interfaceType.NestedTypes
if nestedTypes == nil {
continue
}

nestedTypes.Foreach(func(_ string, nestedType Type) {
nestedInterfaceType, ok := nestedType.(*InterfaceType)
if !ok {
return
}

interfaceTypes = append(interfaceTypes, nestedInterfaceType)
})
}
turbolent marked this conversation as resolved.
Show resolved Hide resolved
}
4 changes: 4 additions & 0 deletions runtime/sema/type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2378,6 +2378,10 @@ func TestTypeInclusions(t *testing.T) {
return
}

if _, ok := typ.(*InterfaceType); ok {
return
}

if typ.IsResourceType() {
return
}
Expand Down
68 changes: 68 additions & 0 deletions runtime/tests/checker/stringer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Cadence - The resource-oriented smart contract programming language
*
* Copyright Dapper Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package checker

import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/onflow/cadence/runtime/sema"
)

func TestCheckStringer(t *testing.T) {

t.Parallel()

_, err := ParseAndCheck(t, `
let a: {Stringer} = 1
let b: {Stringer} = false
let c: {Stringer} = "hey"
access(all)
struct Foo: Stringer {
view fun toString():String {
return "foo"
}
}
let d: {Stringer} = Foo()
`)

assert.NoError(t, err)
}

func TestCheckInvalidStringer(t *testing.T) {

t.Parallel()

_, err := ParseAndCheck(t, `
resource R {}

let a: {Stringer} = <-create R()
let b: {Stringer} = [<-create R()]
let c: {Stringer} = {1: true}
struct Foo: Stringer {}
`)

errs := RequireCheckerErrors(t, err, 4)

assert.IsType(t, &sema.TypeMismatchError{}, errs[0])
assert.IsType(t, &sema.TypeMismatchError{}, errs[1])
assert.IsType(t, &sema.TypeMismatchError{}, errs[2])
assert.IsType(t, &sema.ConformanceError{}, errs[3])
}
78 changes: 78 additions & 0 deletions runtime/tests/interpreter/stringer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Cadence - The resource-oriented smart contract programming language
*
* Copyright Flow Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package interpreter_test

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/onflow/cadence/runtime/interpreter"
. "github.com/onflow/cadence/runtime/tests/utils"
)

func TestStringerBasic(t *testing.T) {

t.Parallel()

inter := parseCheckAndInterpret(t, `
access(all)
struct Example: Stringer {
view fun toString():String {
return "example"
}
}
fun test() :String {
return Example().toString()
}
SupunS marked this conversation as resolved.
Show resolved Hide resolved
`)

result, err := inter.Invoke("test")
require.NoError(t, err)

RequireValuesEqual(
t,
inter,
interpreter.NewUnmeteredStringValue("example"),
result,
)
}

func TestStringerBuiltIn(t *testing.T) {

t.Parallel()

inter := parseCheckAndInterpret(t, `
access(all)
fun test() :String {
SupunS marked this conversation as resolved.
Show resolved Hide resolved
let v = 1
return v.toString()
}
`)

result, err := inter.Invoke("test")
require.NoError(t, err)

RequireValuesEqual(
t,
inter,
interpreter.NewUnmeteredStringValue("1"),
result,
)
}
SupunS marked this conversation as resolved.
Show resolved Hide resolved
Loading