fix: nil pointer

This commit is contained in:
Young Xu 2023-03-18 22:59:58 +08:00
parent 1f614fadb9
commit b74a5040b3
Signed by: xuthus5
GPG Key ID: A23CF9620CBB55F9
4 changed files with 24 additions and 19 deletions

View File

@ -10,6 +10,7 @@ import (
type Parser struct {
source *os.File
debug bool
}
type Defines struct {
@ -39,7 +40,9 @@ func (ps *Parser) Parse() (*Defines, error) {
return nil, err
}
//ast.Print(tokenSet, astFile)
if ps.debug {
_ = ast.Print(tokenSet, astFile)
}
var defines = &Defines{
variable: make(map[string]struct{}),
@ -86,6 +89,10 @@ func (ps *Parser) Parse() (*Defines, error) {
return defines, nil
}
func (ps *Parser) Debug() {
ps.debug = true
}
func (d *Defines) ExistVariable(name string) bool {
_, exist := d.variable[name]
return exist

View File

@ -2,14 +2,15 @@ package goast_test
import (
"fmt"
"gitter.top/coco/goast"
"testing"
"github.com/stretchr/testify/assert"
"gitter.top/coco/goast"
)
func TestParser_Parse(t *testing.T) {
parser, err := goast.NewParser("./testdata/main.go")
parser.Debug()
assert.NoError(t, err)
defines, err := parser.Parse()
assert.NoError(t, err)

18
testdata/main.go vendored
View File

@ -1,19 +1,7 @@
package goast
import (
_ "github.com/stretchr/testify"
)
var a = 1
const d = "world"
func hello() {
}
type c int
func (cc c) name() {
import "os"
type ExampleService struct {
os.File
}

13
util.go
View File

@ -4,7 +4,10 @@ import "go/ast"
// getKVFromImportSpec get import name and package path from *ast.ImportSpec
func getKVFromImportSpec(impt *ast.ImportSpec) (string, string) {
name := impt.Name.Name
var name string
if impt.Name != nil {
name = impt.Name.Name
}
pkg := impt.Path.Value
return name, pkg
}
@ -19,7 +22,13 @@ func getKVFromValueSpec(spec *ast.ValueSpec) (string, string) {
// getKVFromTypeSpec get type name and base type from *ast.TypeSpec
func getKVFromTypeSpec(spec *ast.TypeSpec) (string, string) {
name := spec.Name.Name
value := spec.Type.(*ast.Ident).Name
var value string
switch spec.Type.(type) {
case *ast.Ident:
value = spec.Type.(*ast.Ident).Name
case *ast.StructType:
value = "raw"
}
return name, value
}