Skip to content

Commit

Permalink
feat: use PackageClauseOnly for parsing pkg name (gnolang#994)
Browse files Browse the repository at this point in the history
  • Loading branch information
harry-hov authored and Doozers committed Aug 31, 2023
1 parent 182606b commit 62cfe36
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions gnovm/pkg/gnolang/nodes.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package gnolang

import (
"fmt"
"go/parser"
"go/token"
"io/ioutil"
"os"
"path/filepath"
Expand Down Expand Up @@ -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.
Expand All @@ -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",
Expand All @@ -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(), ".") ||
Expand Down

0 comments on commit 62cfe36

Please sign in to comment.