Merge pull request #1295 from nspcc-dev/fix/seqpoints

Add non-main package files in DebugInfo.Documents
This commit is contained in:
Roman Khimov 2020-08-11 18:12:47 +03:00 committed by GitHub
commit a17e7b7269
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 117 additions and 60 deletions

View file

@ -1,7 +1,6 @@
package smartcontract package smartcontract
import ( import (
"bytes"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
@ -563,12 +562,10 @@ func inspect(ctx *cli.Context) error {
if len(in) == 0 { if len(in) == 0 {
return cli.NewExitError(errNoInput, 1) return cli.NewExitError(errNoInput, 1)
} }
b, err := ioutil.ReadFile(in) var b []byte
if err != nil { var err error
return cli.NewExitError(err, 1)
}
if compile { if compile {
b, err = compiler.Compile(bytes.NewReader(b)) b, err = compiler.Compile(in, nil)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to compile: %w", err), 1) return cli.NewExitError(fmt.Errorf("failed to compile: %w", err), 1)
} }

View file

@ -45,6 +45,12 @@ By default the filename will be the name of your .go file with the .nef extensio
./bin/neo-go contract compile -i mycontract.go --out /Users/foo/bar/contract.nef ./bin/neo-go contract compile -i mycontract.go --out /Users/foo/bar/contract.nef
``` ```
If you contract is split across multiple files, you must provide a path
to the directory where package files are contained instead of a single Go file:
```
./bin/neo-go contract compile -i ./path/to/contract
```
### Debugging ### Debugging
You can dump the opcodes generated by the compiler with the following command: You can dump the opcodes generated by the compiler with the following command:

View file

@ -3,6 +3,7 @@ package compiler
import ( import (
"errors" "errors"
"go/ast" "go/ast"
"go/token"
"go/types" "go/types"
"strings" "strings"
@ -163,6 +164,16 @@ func (c *codegen) visitPkg(pkg *types.Package, seen map[string]bool) {
c.packages = append(c.packages, pkgPath) c.packages = append(c.packages, pkgPath)
} }
func (c *codegen) fillDocumentInfo() {
fset := c.buildInfo.program.Fset
fset.Iterate(func(f *token.File) bool {
filePath := f.Position(f.Pos(0)).Filename
c.docIndex[filePath] = len(c.documents)
c.documents = append(c.documents, filePath)
return true
})
}
func (c *codegen) analyzeFuncUsage() funcUsage { func (c *codegen) analyzeFuncUsage() funcUsage {
usage := funcUsage{} usage := funcUsage{}

View file

@ -77,6 +77,11 @@ type codegen struct {
// packages contains packages in the order they were loaded. // packages contains packages in the order they were loaded.
packages []string packages []string
// documents contains paths to all files used by the program.
documents []string
// docIndex maps file path to an index in documents array.
docIndex map[string]int
// Label table for recording jump destinations. // Label table for recording jump destinations.
l []int l []int
} }
@ -395,6 +400,9 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
// x = 2 // x = 2
// ) // )
case *ast.GenDecl: case *ast.GenDecl:
if n.Tok == token.VAR || n.Tok == token.CONST {
c.saveSequencePoint(n)
}
if n.Tok == token.CONST { if n.Tok == token.CONST {
for _, spec := range n.Specs { for _, spec := range n.Specs {
vs := spec.(*ast.ValueSpec) vs := spec.(*ast.ValueSpec)
@ -1541,6 +1549,7 @@ func (c *codegen) newLambda(u uint16, lit *ast.FuncLit) {
func (c *codegen) compile(info *buildInfo, pkg *loader.PackageInfo) error { func (c *codegen) compile(info *buildInfo, pkg *loader.PackageInfo) error {
c.mainPkg = pkg c.mainPkg = pkg
c.analyzePkgOrder() c.analyzePkgOrder()
c.fillDocumentInfo()
funUsage := c.analyzeFuncUsage() funUsage := c.analyzeFuncUsage()
// Bring all imported functions into scope. // Bring all imported functions into scope.
@ -1588,6 +1597,7 @@ func newCodegen(info *buildInfo, pkg *loader.PackageInfo) *codegen {
labels: map[labelWithType]uint16{}, labels: map[labelWithType]uint16{},
typeInfo: &pkg.Info, typeInfo: &pkg.Info,
constMap: map[string]types.TypeAndValue{}, constMap: map[string]types.TypeAndValue{},
docIndex: map[string]int{},
sequencePoints: make(map[string][]DebugSeqPoint), sequencePoints: make(map[string][]DebugSeqPoint),
} }

View file

@ -1,8 +1,8 @@
package compiler package compiler
import ( import (
"bytes"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"go/ast" "go/ast"
"go/parser" "go/parser"
@ -10,7 +10,7 @@ import (
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path"
"strings" "strings"
"github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract"
@ -84,13 +84,34 @@ func (c *codegen) fillImportMap(f *ast.File, pkg *types.Package) {
} }
} }
func getBuildInfo(src interface{}) (*buildInfo, error) { func getBuildInfo(name string, src interface{}) (*buildInfo, error) {
conf := loader.Config{ParserMode: parser.ParseComments} conf := loader.Config{ParserMode: parser.ParseComments}
f, err := conf.ParseFile("", src) if src != nil {
if err != nil { f, err := conf.ParseFile(name, src)
return nil, err if err != nil {
return nil, err
}
conf.CreateFromFiles("", f)
} else {
var names []string
if strings.HasSuffix(name, ".go") {
names = append(names, name)
} else {
ds, err := ioutil.ReadDir(name)
if err != nil {
return nil, fmt.Errorf("'%s' is neither Go source nor a directory", name)
}
for i := range ds {
if !ds[i].IsDir() && strings.HasSuffix(ds[i].Name(), ".go") {
names = append(names, path.Join(name, ds[i].Name()))
}
}
}
if len(names) == 0 {
return nil, errors.New("no files provided")
}
conf.CreateFromFilenames("", names...)
} }
conf.CreateFromFiles("", f)
prog, err := conf.Load() prog, err := conf.Load()
if err != nil { if err != nil {
@ -98,14 +119,16 @@ func getBuildInfo(src interface{}) (*buildInfo, error) {
} }
return &buildInfo{ return &buildInfo{
initialPackage: f.Name.Name, initialPackage: prog.InitialPackages()[0].Pkg.Name(),
program: prog, program: prog,
}, nil }, nil
} }
// Compile compiles a Go program into bytecode that can run on the NEO virtual machine. // Compile compiles a Go program into bytecode that can run on the NEO virtual machine.
func Compile(r io.Reader) ([]byte, error) { // If `r != nil`, `name` is interpreted as a filename, and `r` as file contents.
buf, _, err := CompileWithDebugInfo(r) // Otherwise `name` is either file name or name of the directory containing source files.
func Compile(name string, r io.Reader) ([]byte, error) {
buf, _, err := CompileWithDebugInfo(name, r)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -114,8 +137,8 @@ func Compile(r io.Reader) ([]byte, error) {
} }
// CompileWithDebugInfo compiles a Go program into bytecode and emits debug info. // CompileWithDebugInfo compiles a Go program into bytecode and emits debug info.
func CompileWithDebugInfo(r io.Reader) ([]byte, *DebugInfo, error) { func CompileWithDebugInfo(name string, r io.Reader) ([]byte, *DebugInfo, error) {
ctx, err := getBuildInfo(r) ctx, err := getBuildInfo(name, r)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -124,21 +147,18 @@ func CompileWithDebugInfo(r io.Reader) ([]byte, *DebugInfo, error) {
// CompileAndSave will compile and save the file to disk in the NEF format. // CompileAndSave will compile and save the file to disk in the NEF format.
func CompileAndSave(src string, o *Options) ([]byte, error) { func CompileAndSave(src string, o *Options) ([]byte, error) {
if !strings.HasSuffix(src, ".go") {
return nil, fmt.Errorf("%s is not a Go file", src)
}
o.Outfile = strings.TrimSuffix(o.Outfile, fmt.Sprintf(".%s", fileExt)) o.Outfile = strings.TrimSuffix(o.Outfile, fmt.Sprintf(".%s", fileExt))
if len(o.Outfile) == 0 { if len(o.Outfile) == 0 {
o.Outfile = strings.TrimSuffix(src, ".go") if strings.HasSuffix(src, ".go") {
o.Outfile = strings.TrimSuffix(src, ".go")
} else {
o.Outfile = "out"
}
} }
if len(o.Ext) == 0 { if len(o.Ext) == 0 {
o.Ext = fileExt o.Ext = fileExt
} }
b, err := ioutil.ReadFile(src) b, di, err := CompileWithDebugInfo(src, nil)
if err != nil {
return nil, err
}
b, di, err := CompileWithDebugInfo(bytes.NewReader(b))
if err != nil { if err != nil {
return nil, fmt.Errorf("error while trying to compile smart contract file: %w", err) return nil, fmt.Errorf("error while trying to compile smart contract file: %w", err)
} }
@ -159,12 +179,6 @@ func CompileAndSave(src string, o *Options) ([]byte, error) {
return b, nil return b, nil
} }
p, err := filepath.Abs(src)
if err != nil {
return b, err
}
di.Documents = append(di.Documents, p)
if o.DebugInfo != "" { if o.DebugInfo != "" {
data, err := json.Marshal(di) data, err := json.Marshal(di)
if err != nil { if err != nil {

View file

@ -24,6 +24,20 @@ func TestCompiler(t *testing.T) {
// CompileAndSave use config.Version for proper .nef generation. // CompileAndSave use config.Version for proper .nef generation.
config.Version = "0.90.0-test" config.Version = "0.90.0-test"
testCases := []compilerTestCase{ testCases := []compilerTestCase{
{
name: "TestCompileDirectory",
function: func(t *testing.T) {
const multiMainDir = "testdata/multi"
_, di, err := compiler.CompileWithDebugInfo(multiMainDir, nil)
require.NoError(t, err)
m := map[string]bool{}
for i := range di.Methods {
m[di.Methods[i].Name.Name] = true
}
require.Contains(t, m, "Func1")
require.Contains(t, m, "Func2")
},
},
{ {
name: "TestCompile", name: "TestCompile",
function: func(t *testing.T) { function: func(t *testing.T) {
@ -73,10 +87,6 @@ func filterFilename(infos []os.FileInfo) string {
} }
func compileFile(src string) error { func compileFile(src string) error {
file, err := os.Open(src) _, err := compiler.Compile(src, nil)
if err != nil {
return err
}
_, err = compiler.Compile(file)
return err return err
} }

View file

@ -85,15 +85,17 @@ type DebugParam struct {
} }
func (c *codegen) saveSequencePoint(n ast.Node) { func (c *codegen) saveSequencePoint(n ast.Node) {
if c.scope == nil { name := "init"
// do not save globals for now if c.scope != nil {
return name = c.scope.name
} }
fset := c.buildInfo.program.Fset fset := c.buildInfo.program.Fset
start := fset.Position(n.Pos()) start := fset.Position(n.Pos())
end := fset.Position(n.End()) end := fset.Position(n.End())
c.sequencePoints[c.scope.name] = append(c.sequencePoints[c.scope.name], DebugSeqPoint{ c.sequencePoints[name] = append(c.sequencePoints[name], DebugSeqPoint{
Opcode: c.prog.Len(), Opcode: c.prog.Len(),
Document: c.docIndex[start.Filename],
StartLine: start.Line, StartLine: start.Line,
StartCol: start.Offset, StartCol: start.Offset,
EndLine: end.Line, EndLine: end.Line,
@ -103,9 +105,10 @@ func (c *codegen) saveSequencePoint(n ast.Node) {
func (c *codegen) emitDebugInfo(contract []byte) *DebugInfo { func (c *codegen) emitDebugInfo(contract []byte) *DebugInfo {
d := &DebugInfo{ d := &DebugInfo{
MainPkg: c.mainPkg.Pkg.Name(), MainPkg: c.mainPkg.Pkg.Name(),
Hash: hash.Hash160(contract), Hash: hash.Hash160(contract),
Events: []EventDebugInfo{}, Events: []EventDebugInfo{},
Documents: c.documents,
} }
if c.initEndOffset > 0 { if c.initEndOffset > 0 {
d.Methods = append(d.Methods, MethodDebugInfo{ d.Methods = append(d.Methods, MethodDebugInfo{
@ -120,6 +123,7 @@ func (c *codegen) emitDebugInfo(contract []byte) *DebugInfo {
End: uint16(c.initEndOffset), End: uint16(c.initEndOffset),
}, },
ReturnType: "Void", ReturnType: "Void",
SeqPoints: c.sequencePoints["init"],
}) })
} }
for name, scope := range c.funcs { for name, scope := range c.funcs {

View file

@ -44,7 +44,7 @@ func MethodStruct() struct{} { return struct{}{} }
func unexportedMethod() int { return 1 } func unexportedMethod() int { return 1 }
` `
info, err := getBuildInfo(src) info, err := getBuildInfo("foo.go", src)
require.NoError(t, err) require.NoError(t, err)
pkg := info.program.Package(info.initialPackage) pkg := info.program.Package(info.initialPackage)
@ -238,7 +238,7 @@ func TestSequencePoints(t *testing.T) {
return false return false
}` }`
info, err := getBuildInfo(src) info, err := getBuildInfo("foo.go", src)
require.NoError(t, err) require.NoError(t, err)
pkg := info.program.Package(info.initialPackage) pkg := info.program.Package(info.initialPackage)
@ -249,6 +249,8 @@ func TestSequencePoints(t *testing.T) {
d := c.emitDebugInfo(buf) d := c.emitDebugInfo(buf)
require.NotNil(t, d) require.NotNil(t, d)
require.Equal(t, d.Documents, []string{"foo.go"})
// Main func has 2 return on 4-th and 6-th lines. // Main func has 2 return on 4-th and 6-th lines.
ps := d.Methods[0].SeqPoints ps := d.Methods[0].SeqPoints
require.Equal(t, 2, len(ps)) require.Equal(t, 2, len(ps))

View file

@ -118,7 +118,7 @@ func TestContractWithNoMain(t *testing.T) {
someLocal := 2 someLocal := 2
return someGlobal + someLocal + a return someGlobal + someLocal + a
}` }`
b, di, err := compiler.CompileWithDebugInfo(strings.NewReader(src)) b, di, err := compiler.CompileWithDebugInfo("foo.go", strings.NewReader(src))
require.NoError(t, err) require.NoError(t, err)
v := vm.New() v := vm.New()
invokeMethod(t, "Add3", b, v, di) invokeMethod(t, "Add3", b, v, di)

View file

@ -63,7 +63,7 @@ func TestFromAddress(t *testing.T) {
} }
func spawnVM(t *testing.T, ic *interop.Context, src string) *vm.VM { func spawnVM(t *testing.T, ic *interop.Context, src string) *vm.VM {
b, di, err := compiler.CompileWithDebugInfo(strings.NewReader(src)) b, di, err := compiler.CompileWithDebugInfo("foo.go", strings.NewReader(src))
require.NoError(t, err) require.NoError(t, err)
v := core.SpawnVM(ic) v := core.SpawnVM(ic)
invokeMethod(t, testMainIdent, b, v, di) invokeMethod(t, testMainIdent, b, v, di)
@ -86,7 +86,7 @@ func TestAppCall(t *testing.T) {
} }
` `
inner, di, err := compiler.CompileWithDebugInfo(strings.NewReader(srcInner)) inner, di, err := compiler.CompileWithDebugInfo("foo.go", strings.NewReader(srcInner))
require.NoError(t, err) require.NoError(t, err)
m, err := di.ConvertToManifest(smartcontract.NoProperties) m, err := di.ConvertToManifest(smartcontract.NoProperties)
require.NoError(t, err) require.NoError(t, err)

View file

@ -3,3 +3,7 @@ package multi
var SomeVar12 = 12 var SomeVar12 = 12
const SomeConst = 42 const SomeConst = 42
func Func1() bool {
return true
}

View file

@ -5,3 +5,7 @@ var SomeVar30 = 30
func Sum() int { func Sum() int {
return SomeVar12 + SomeVar30 return SomeVar12 + SomeVar30
} }
func Func2() bool {
return false
}

View file

@ -72,7 +72,7 @@ func vmAndCompileInterop(t *testing.T, src string) (*vm.VM, *storagePlugin) {
vm.GasLimit = -1 vm.GasLimit = -1
vm.SyscallHandler = storePlugin.syscallHandler vm.SyscallHandler = storePlugin.syscallHandler
b, di, err := compiler.CompileWithDebugInfo(strings.NewReader(src)) b, di, err := compiler.CompileWithDebugInfo("foo.go", strings.NewReader(src))
require.NoError(t, err) require.NoError(t, err)
invokeMethod(t, testMainIdent, b, vm, di) invokeMethod(t, testMainIdent, b, vm, di)

View file

@ -225,9 +225,10 @@ func TestCreateBasicChain(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
// Push some contract into the chain. // Push some contract into the chain.
c, err := ioutil.ReadFile(prefix + "test_contract.go") name := prefix + "test_contract.go"
c, err := ioutil.ReadFile(name)
require.NoError(t, err) require.NoError(t, err)
avm, di, err := compiler.CompileWithDebugInfo(bytes.NewReader(c)) avm, di, err := compiler.CompileWithDebugInfo(name, bytes.NewReader(c))
require.NoError(t, err) require.NoError(t, err)
t.Logf("contractHash: %s", hash.Hash160(avm).StringLE()) t.Logf("contractHash: %s", hash.Hash160(avm).StringLE())

View file

@ -6,7 +6,6 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"strconv" "strconv"
@ -306,12 +305,7 @@ func handleLoadGo(c *ishell.Context) {
c.Err(errors.New("missing parameter <file>")) c.Err(errors.New("missing parameter <file>"))
return return
} }
fb, err := ioutil.ReadFile(c.Args[0]) b, err := compiler.Compile(c.Args[0], nil)
if err != nil {
c.Err(err)
return
}
b, err := compiler.Compile(bytes.NewReader(fb))
if err != nil { if err != nil {
c.Err(err) c.Err(err)
return return