From 96fa855d4d929fffd843a9e7533aa49c2cd3d950 Mon Sep 17 00:00:00 2001 From: Hariom Verma Date: Wed, 26 Jul 2023 19:04:08 +0530 Subject: [PATCH] feat: use `PackageClauseOnly` for parsing pkg name --- 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(), ".") ||