| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
// Package decls provides a set of functions to parse and analyze Go source |
| 5 |
// code and get the declarations within it. |
| 6 |
package decls // import "go.opentelemetry.io/otel/internal/tools/semconvkit/decls" |
| 7 |
|
| 8 |
import ( |
| 9 |
"go/ast" |
| 10 |
"go/parser" |
| 11 |
"go/token" |
| 12 |
"strings" |
| 13 |
) |
| 14 |
|
| 15 |
// GetNames parses the Go source code in the specified package path and returns |
| 16 |
// the names extracted from the declarations using the provided parser |
| 17 |
// function. |
| 18 |
// |
| 19 |
// The names are returned as a map where the keys are the names fully |
| 20 |
// lowercased form of the name and the values are the original format of the |
| 21 |
// name. |
| 22 |
func GetNames(pkgPath string, f Parser) (Names, error) { |
| 23 |
fset := token.NewFileSet() |
| 24 |
pkgs, err := parser.ParseDir(fset, pkgPath, nil, 0) |
| 25 |
if err != nil { |
| 26 |
return nil, err |
| 27 |
} |
| 28 |
|
| 29 |
out := make(Names) |
| 30 |
for _, pkg := range pkgs { |
| 31 |
for _, file := range pkg.Files { |
| 32 |
for _, decl := range file.Decls { |
| 33 |
for _, name := range f(decl) { |
| 34 |
out[NewCanonicalName(name)] = Name(name) |
| 35 |
} |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
return out, nil |
| 40 |
} |
| 41 |
|
| 42 |
// Parser is a function type that takes an [ast.Decl] and returns a slice of |
| 43 |
// parsed string identifiers. |
| 44 |
type Parser func(ast.Decl) []string |
| 45 |
|
| 46 |
// CanonicalName is the canonical form of a name (lowercase). |
| 47 |
type CanonicalName string |
| 48 |
|
| 49 |
// NewCanonicalName returns name as a [CanonicalName]. |
| 50 |
func NewCanonicalName(name string) CanonicalName { |
| 51 |
return CanonicalName(strings.ToLower(name)) |
| 52 |
} |
| 53 |
|
| 54 |
// Name is the original form of a name (case-sensitive). |
| 55 |
type Name string |
| 56 |
|
| 57 |
// Names is a map of canonical names to their original names. |
| 58 |
type Names map[CanonicalName]Name |