Skip to content

Commit

Permalink
add methods to obtain sorted namelist of values, types, functions
Browse files Browse the repository at this point in the history
  • Loading branch information
koron committed Mar 30, 2024
1 parent a685203 commit bad4cbb
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions srcdom.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package srcdom
import (
"go/ast"
"regexp"
"sort"
"strconv"
"strings"
"unicode"
Expand All @@ -22,13 +23,23 @@ func isPublicName(name string) bool {
return unicode.IsUpper(r)
}

func sortedNames(m map[string]int) []string {
names := make([]string, 0, len(m))
for k := range m {
names = append(names, k)
}
sort.Strings(names)
return names
}

// Package represents a go package.
type Package struct {
Name string

Imports []*Import

Values []*Value
valIdx map[string]int

Funcs []*Func
funIdx map[string]int
Expand All @@ -38,9 +49,28 @@ type Package struct {
}

func (p *Package) putValue(v *Value) {
if p.valIdx == nil {
p.valIdx = make(map[string]int)
}
idx := len(p.Values)
p.valIdx[v.Name] = idx
p.Values = append(p.Values, v)
}

// Value gets a value which matches with name.
func (p *Package) Value(name string) (*Value, bool) {
idx, ok := p.valIdx[name]
if !ok {
return nil, false
}
return p.Values[idx], true
}

// ValueName returns sorted names of value in the package.
func (p *Package) ValueNames() []string {
return sortedNames(p.valIdx)
}

func (p *Package) putFunc(fun *Func) {
if p.funIdx == nil {
p.funIdx = make(map[string]int)
Expand All @@ -59,6 +89,11 @@ func (p *Package) Func(name string) (*Func, bool) {
return p.Funcs[idx], true
}

// FuncNames returns sorted names of function in the package.
func (p *Package) FuncNames() []string {
return sortedNames(p.funIdx)
}

func (p *Package) assureType(name string) *Type {
if typ, ok := p.Type(name); ok {
return typ
Expand Down Expand Up @@ -86,6 +121,11 @@ func (p *Package) Type(name string) (*Type, bool) {
return p.Types[idx], true
}

// TypeNames returns sorted names of type in the package.
func (p *Package) TypeNames() []string {
return sortedNames(p.typIdx)
}

// Import represents an import.
type Import struct {
Name string
Expand Down

0 comments on commit bad4cbb

Please sign in to comment.