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

Import aliasing #3717

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 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
3 changes: 3 additions & 0 deletions ast/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
type ImportDeclaration struct {
Location common.Location
Identifiers []Identifier
Aliases map[string]string
Range
LocationPos Position
}
Expand All @@ -41,6 +42,7 @@ var _ Declaration = &ImportDeclaration{}
func NewImportDeclaration(
gauge common.MemoryGauge,
identifiers []Identifier,
aliases map[string]string,
location common.Location,
declRange Range,
locationPos Position,
Expand All @@ -49,6 +51,7 @@ func NewImportDeclaration(

return &ImportDeclaration{
Identifiers: identifiers,
Aliases: aliases,
Location: location,
Range: declRange,
LocationPos: locationPos,
Expand Down
1 change: 1 addition & 0 deletions ast/import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ func TestImportDeclaration_MarshalJSON(t *testing.T) {
"EndPos": {"Offset": 3, "Line": 2, "Column": 5}
}
],
"Aliases": null,
turbolent marked this conversation as resolved.
Show resolved Hide resolved
"Location": {
"Type": "StringLocation",
"String": "test"
Expand Down
141 changes: 141 additions & 0 deletions interpreter/import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,3 +401,144 @@ func TestInterpretResourceConstructionThroughIndirectImport(t *testing.T) {
resourceConstructionError.CompositeType,
)
}

// TestInterpretImportWithAlias shows importing two funs of the same name from different addresses
turbolent marked this conversation as resolved.
Show resolved Hide resolved
func TestInterpretImportWithAlias(t *testing.T) {

t.Parallel()

address := common.MustBytesToAddress([]byte{0x1})
address2 := common.MustBytesToAddress([]byte{0x2})

importedCheckerA, err := ParseAndCheckWithOptions(t,
`
access(all) fun a(): Int {
return 1
}
`,
ParseAndCheckOptions{
Location: common.AddressLocation{
Address: address,
Name: "",
},
},
)
require.NoError(t, err)

importedCheckerB, err := ParseAndCheckWithOptions(t,
`
access(all) fun a(): Int {
return 2
}
`,
ParseAndCheckOptions{
Location: common.AddressLocation{
Address: address2,
Name: "",
},
},
)
require.NoError(t, err)

importingChecker, err := ParseAndCheckWithOptions(t,
`
import a as a1 from 0x1
import a as a2 from 0x2

access(all) fun test(): Int {
return a1() + a2()
}
`,
ParseAndCheckOptions{
Config: &sema.Config{
LocationHandler: func(identifiers []ast.Identifier, location common.Location) (result []sema.ResolvedLocation, err error) {

for _, identifier := range identifiers {
result = append(result, sema.ResolvedLocation{
Location: common.AddressLocation{
Address: location.(common.AddressLocation).Address,
Name: identifier.Identifier,
},
Identifiers: []ast.Identifier{
identifier,
},
})
}
return
},
ImportHandler: func(checker *sema.Checker, importedLocation common.Location, _ ast.Range) (sema.Import, error) {
require.IsType(t, common.AddressLocation{}, importedLocation)
addressLocation := importedLocation.(common.AddressLocation)

var importedChecker *sema.Checker

switch addressLocation.Address {
case address:
importedChecker = importedCheckerA
case address2:
importedChecker = importedCheckerB
default:
t.Errorf(
"invalid address location location name: %s",
addressLocation.Name,
)
}

return sema.ElaborationImport{
Elaboration: importedChecker.Elaboration,
}, nil
},
},
},
)
require.NoError(t, err)

storage := newUnmeteredInMemoryStorage()

inter, err := interpreter.NewInterpreter(
interpreter.ProgramFromChecker(importingChecker),
importingChecker.Location,
&interpreter.Config{
Storage: storage,
ImportLocationHandler: func(inter *interpreter.Interpreter, location common.Location) interpreter.Import {
require.IsType(t, common.AddressLocation{}, location)
addressLocation := location.(common.AddressLocation)

var importedChecker *sema.Checker

switch addressLocation.Address {
case address:
importedChecker = importedCheckerA
case address2:
importedChecker = importedCheckerB
default:
return nil
}

program := interpreter.ProgramFromChecker(importedChecker)
subInterpreter, err := inter.NewSubInterpreter(program, location)
if err != nil {
panic(err)
}

return interpreter.InterpreterImport{
Interpreter: subInterpreter,
}
},
},
)
require.NoError(t, err)

err = inter.Interpret()
require.NoError(t, err)

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

AssertValuesEqual(
t,
inter,
interpreter.NewUnmeteredIntValueFromInt64(3),
value,
)
}
13 changes: 10 additions & 3 deletions interpreter/interpreter_import.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ func (interpreter *Interpreter) VisitImportDeclaration(declaration *ast.ImportDe
resolvedLocations := interpreter.Program.Elaboration.ImportDeclarationsResolvedLocations(declaration)

for _, resolvedLocation := range resolvedLocations {
interpreter.importResolvedLocation(resolvedLocation)
interpreter.importResolvedLocation(resolvedLocation, &declaration.Aliases)
}

return nil
}

func (interpreter *Interpreter) importResolvedLocation(resolvedLocation sema.ResolvedLocation) {
func (interpreter *Interpreter) importResolvedLocation(resolvedLocation sema.ResolvedLocation, aliases *map[string]string) {
turbolent marked this conversation as resolved.
Show resolved Hide resolved
config := interpreter.SharedState.Config

// tracing
Expand All @@ -62,7 +62,14 @@ func (interpreter *Interpreter) importResolvedLocation(resolvedLocation sema.Res
if identifierLength > 0 {
variables = make(map[string]Variable, identifierLength)
for _, identifier := range resolvedLocation.Identifiers {
variables[identifier.Identifier] =
name := identifier.Identifier
alias, ok := (*aliases)[name]
if ok {
name = alias
}

// map alias to original
variables[name] =
subInterpreter.Globals.Get(identifier.Identifier)
}
} else {
Expand Down
1 change: 1 addition & 0 deletions old_parser/declaration.go
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,7 @@ func parseImportDeclaration(p *parser) (*ast.ImportDeclaration, error) {
return ast.NewImportDeclaration(
p.memoryGauge,
identifiers,
nil,
location,
ast.NewRange(
p.memoryGauge,
Expand Down
51 changes: 47 additions & 4 deletions parser/declaration.go
Original file line number Diff line number Diff line change
Expand Up @@ -645,13 +645,14 @@ func parsePragmaDeclaration(p *parser) (*ast.PragmaDeclaration, error) {
//
// importDeclaration :
// 'import'
// ( identifier (',' identifier)* 'from' )?
// ( identifier (as identifier)? (',' identifier (as identifier)?)* 'from' )?
turbolent marked this conversation as resolved.
Show resolved Hide resolved
// ( string | hexadecimalLiteral | identifier )
func parseImportDeclaration(p *parser) (*ast.ImportDeclaration, error) {

startPosition := p.current.StartPos

var identifiers []ast.Identifier
var aliases map[string]string

var location common.Location
var locationPos ast.Position
Expand Down Expand Up @@ -684,6 +685,36 @@ func parseImportDeclaration(p *parser) (*ast.ImportDeclaration, error) {
endPos = identifier.EndPosition(p.memoryGauge)
}

// pass in the identifier which would be aliased
parseOptionalImportAlias := func(identifier ast.Identifier) error {
// stop early if the current token is not as
if p.current.Type != lexer.TokenIdentifier || string(p.currentTokenSource()) != KeywordAs {
return nil
}
// Skip the `as` keyword
p.nextSemanticToken()

// lazy initialize alias map
if aliases == nil {
aliases = make(map[string]string)
}

switch p.current.Type {
case lexer.TokenIdentifier:
identifierAlias := p.tokenToIdentifier(p.current)
aliases[identifier.Identifier] = identifierAlias.Identifier

// Skip the alias
p.nextSemanticToken()
default:
return p.syntaxError(
"expected identifier in import alias: got %s",
p.current.Type,
)
}
return nil
}

parseLocation := func() error {
switch p.current.Type {
case lexer.TokenString, lexer.TokenHexadecimalIntegerLiteral:
Expand All @@ -705,12 +736,10 @@ func parseImportDeclaration(p *parser) (*ast.ImportDeclaration, error) {
}

parseMoreIdentifiers := func() error {
expectCommaOrFrom := false
expectCommaOrFrom := true

atEnd := false
for !atEnd {
p.nextSemanticToken()

switch p.current.Type {
case lexer.TokenComma:
if !expectCommaOrFrom {
Expand All @@ -722,6 +751,7 @@ func parseImportDeclaration(p *parser) (*ast.ImportDeclaration, error) {
)
}
expectCommaOrFrom = false
p.nextSemanticToken()

case lexer.TokenIdentifier:

Expand Down Expand Up @@ -755,6 +785,13 @@ func parseImportDeclaration(p *parser) (*ast.ImportDeclaration, error) {

identifier := p.tokenToIdentifier(p.current)
identifiers = append(identifiers, identifier)
p.nextSemanticToken()

// Parse optional alias
err := parseOptionalImportAlias(identifier)
if err != nil {
return err
}

expectCommaOrFrom = true

Expand Down Expand Up @@ -813,6 +850,11 @@ func parseImportDeclaration(p *parser) (*ast.ImportDeclaration, error) {
identifier := p.tokenToIdentifier(p.current)
// Skip the identifier
p.nextSemanticToken()
// Parse optional alias
err := parseOptionalImportAlias(identifier)
if err != nil {
return nil, err
}

switch p.current.Type {
case lexer.TokenComma:
Expand Down Expand Up @@ -854,6 +896,7 @@ func parseImportDeclaration(p *parser) (*ast.ImportDeclaration, error) {
return ast.NewImportDeclaration(
p.memoryGauge,
identifiers,
aliases,
location,
ast.NewRange(
p.memoryGauge,
Expand Down
Loading
Loading