From 62cfe360eaf632da0ab3f7a99ff5465f0454edb1 Mon Sep 17 00:00:00 2001 From: Hariom Verma Date: Thu, 10 Aug 2023 21:51:56 +0530 Subject: [PATCH] feat: use `PackageClauseOnly` for parsing pkg name (#994) --- gnovm/pkg/gnolang/nodes.go | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/gnovm/pkg/gnolang/nodes.go b/gnovm/pkg/gnolang/nodes.go index e838ba562c0..18a9b1ece52 100644 --- a/gnovm/pkg/gnolang/nodes.go +++ b/gnovm/pkg/gnolang/nodes.go @@ -2,6 +2,8 @@ package gnolang import ( "fmt" + "go/parser" + "go/token" "io/ioutil" "os" "path/filepath" @@ -1079,14 +1081,16 @@ type FileSet struct { Files []*FileNode } -// TODO replace with some more efficient method -// that doesn't involve parsing the whole file. -// -// name could be anything, -// it's only used to generate better error traces. -func PackageNameFromFileBody(name string, body string) Name { - n := MustParseFile(name, body) - return n.PkgName +// PackageNameFromFileBody extracts the package name from the given Gno code body. +// The 'name' parameter is used for better error traces, and 'body' contains the Gno code. +func PackageNameFromFileBody(name, body string) Name { + fset := token.NewFileSet() + astFile, err := parser.ParseFile(fset, name, body, parser.PackageClauseOnly) + if err != nil { + panic(err) + } + + return Name(astFile.Name.Name) } // NOTE: panics if package name is invalid. @@ -1096,7 +1100,6 @@ func ReadMemPackage(dir string, pkgPath string) *std.MemPackage { panic(err) } memPkg := &std.MemPackage{Path: pkgPath} - var pkgName Name allowedFiles := []string{ // make case insensitive? "gno.mod", "LICENSE", @@ -1105,6 +1108,7 @@ func ReadMemPackage(dir string, pkgPath string) *std.MemPackage { allowedFileExtensions := []string{ ".gno", } + var pkgName Name for _, file := range files { if file.IsDir() || strings.HasPrefix(file.Name(), ".") ||