enumgen

package
v0.9.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2023 License: BSD-3-Clause Imports: 17 Imported by: 2

Documentation

Overview

Package enumgen provides functions for generating enum methods for enum types.

Index

Constants

View Source
const JSONMethods = `` /* 432-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringBelongsMethodLoop = `` /* 192-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringDescMethod = `` /* 158-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringDescsMethod = `` /* 216-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringHasBitFlagMethod = `` /* 191-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringInt64Method = `// Int64 returns the %[1]s value as an int64.
func (i %[1]s) Int64() int64 {
	return int64(i)
}
`

Arguments to format are:

[1]: type name
View Source
const StringIsValidMethod = `` /* 143-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringMap = `` /* 210-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringNConstant = `//%[1]sN is the total number of
// enum values for type %[1]s.
const %[1]sN %[1]s = %[2]d
`

Arguments to format are:

[1]: type name
[2]: number of constants for type
View Source
const StringOneRun = `` /* 258-byte string literal not displayed */

Arguments to format are:

[1]: type name
[2]: size of index element (8 for uint8 etc.)
[3]: less than zero check (for signed types)
View Source
const StringOneRunWithOffset = `` /* 280-byte string literal not displayed */

Arguments to format are:

[1]: type name
[2]: lowest defined value for type, as a string
[3]: size of index element (8 for uint8 etc.)
[4]: less than zero check (for signed types)
View Source
const StringSetBitFlagMethod = `` /* 347-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringSetInt64Method = `// SetInt64 sets the %[1]s value from an int64.
func (i *%[1]s) SetInt64(in int64) {
	*i = %[1]s(in)
}
`

Arguments to format are:

[1]: type name
View Source
const StringSetStringMethod = `` /* 384-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringStringsMethod = `` /* 227-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringValuesGlobal = `` /* 230-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const StringValuesMethod = `` /* 287-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const TextMethods = `` /* 306-byte string literal not displayed */

Arguments to format are:

[1]: type name
View Source
const YAMLMethods = `` /* 323-byte string literal not displayed */

Arguments to format are:

[1]: type name

Variables

View Source
var AllowedEnumTypes = map[string]bool{"int": true, "int64": true, "int32": true, "int16": true, "int8": true, "uint": true, "uint64": true, "uint32": true, "uint16": true, "uint8": true}

AllowedEnumTypes are the types that can be used for enums that are not bit flags (bit flags can only be int64s). It is stored as a map for quick and convenient access.

Functions

func Generate

func Generate(config Config) error

Generate generates enum methods using the given configuration object. It reads all Go files in the config source directory and writes the result to the config output file. It is a simple entry point to enumgen that does all of the steps; for more specific functionality, create a new Generator with NewGenerator and call methods on it.

func SplitIntoRuns

func SplitIntoRuns(values []Value) [][]Value

SplitIntoRuns breaks the values into runs of contiguous sequences. For example, given 1,2,3,5,6,7 it returns {1,2,3},{5,6,7}. The input slice is known to be non-empty.

func Usize

func Usize(n int) int

Usize returns the number of bits of the smallest unsigned integer type that will hold n. Used to create the smallest possible slice of integers to use as indexes into the concatenated strings.

Types

type ByValue

type ByValue []Value

ByValue is a sorting method that sorts the constants into increasing order. We take care in the Less method to sort in signed or unsigned order, as appropriate.

func (ByValue) Len

func (b ByValue) Len() int

func (ByValue) Less

func (b ByValue) Less(i, j int) bool

func (ByValue) Swap

func (b ByValue) Swap(i, j int)

type Config

type Config struct {
	Dir         string // the source directory
	Output      string // the output file
	SQL         bool   // whether to generate methods that implement the SQL Scanner and Valuer interfaces
	Text        bool   // whether to generate text marshaling methods
	JSON        bool   // whether to generate JSON marshaling methods  (note that text marshaling methods will also work for JSON, so this should be unnecessary in almost all cases; see [Config.Text])
	YAML        bool   // whether to generate YAML marshaling methods
	GQLGEN      bool   // whether to generate GraphQL marshaling methods for gqlgen
	Transform   string // if specified, the enum item transformation method (eg: snake_case)
	TrimPrefix  string // if specified, a comma-separated list of prefixes to trim from each item
	AddPrefix   string // if specified, the prefix to add to each item
	LineComment bool   // whether to use line comment text as printed text when present
	Comment     string // a comment to include at the top of the generated code
}

Config contains the configuration information used by enumgen

func (*Config) Defaults

func (c *Config) Defaults()

Defaults applies the default configuration values to the configuration object. It only sets some values; if you want to reset the configuration object, you should do that manually first.

type File

type File struct {
	Pkg  *Package  // Package to which this file belongs.
	File *ast.File // Parsed AST.
	// These fields are reset for each type being generated.
	TypeName string  // The name of the constant type we are currently looking for.
	BitFlag  bool    // Whether the constant type we are currently looking for is a bitflag.
	Values   []Value // Accumulator for constant values of that type.
	Config   Config  // The configuration information
}

File holds a single parsed file and associated data.

func (*File) GenDecl

func (f *File) GenDecl(node ast.Node) (bool, error)

GenDecl processes one declaration clause. It returns whether the AST inspector should continue, and an error if there is one. It should only be called in ast.Inspect.

type Generator

type Generator struct {
	Config     Config       // The configuration information
	Buf        bytes.Buffer // The accumulated output.
	Pkg        *Package     // The package we are scanning.
	Types      []Type       // The enum types
	HasBitFlag bool         // Whether there is any bit flag enum type in the package (used for determining imports)
}

Generator holds the state of the generator. It is primarily used to buffer the output for [format.Source].

func NewGenerator

func NewGenerator(config Config) *Generator

NewGenerator returns a new generator with the given configuration information.

func (*Generator) AddPackage

func (g *Generator) AddPackage(pkg *packages.Package)

AddPackage adds a type-checked Package and its syntax files to the generator.

func (*Generator) BuildBasicExtras

func (g *Generator) BuildBasicExtras(runs [][]Value, typeName string, runsThreshold int)

BuildBasicExtras builds methods common to all types, like Desc and SetString.

func (*Generator) BuildBitFlagMethods

func (g *Generator) BuildBitFlagMethods(runs [][]Value, typeName string)

BuildBitFlagMethods builds methods specific to bit flag types.

func (*Generator) BuildJSONMethods

func (g *Generator) BuildJSONMethods(runs [][]Value, typeName string, runsThreshold int)

func (*Generator) BuildMap

func (g *Generator) BuildMap(runs [][]Value, typeName string)

BuildMap handles the case where the space is so sparse a map is a reasonable fallback. It's a rare situation but has simple code.

func (*Generator) BuildMultipleRuns

func (g *Generator) BuildMultipleRuns(runs [][]Value, typeName string)

BuildMultipleRuns generates the variables and String method for multiple runs of contiguous values. For this pattern, a single Printf format won't do.

func (*Generator) BuildNoOpOrderChangeDetect

func (g *Generator) BuildNoOpOrderChangeDetect(runs [][]Value, typeName string)

BuildNoOpOrderChangeDetect try to let the compiler and the user know if the order/value of the ENUMS have changed.

func (*Generator) BuildOneRun

func (g *Generator) BuildOneRun(runs [][]Value, typeName string)

BuildOneRun generates the variables and String method for a single run of contiguous values.

func (*Generator) BuildTextMethods

func (g *Generator) BuildTextMethods(runs [][]Value, typeName string, runsThreshold int)

func (*Generator) BuildYAMLMethods

func (g *Generator) BuildYAMLMethods(runs [][]Value, typeName string, runsThreshold int)

func (*Generator) CreateIndexAndNameDecl

func (g *Generator) CreateIndexAndNameDecl(run []Value, typeName string, suffix string) (string, string)

CreateIndexAndNameDecl returns the pair of declarations for the run. The caller will add "const" and "var".

func (*Generator) CreateLowerIndexAndNameDecl

func (g *Generator) CreateLowerIndexAndNameDecl(run []Value, typeName string, suffix string) (string, string)

createIndexAndNameDecl returns the pair of declarations for the run. The caller will add "const" and "var".

func (*Generator) DeclareIndexAndNameVar

func (g *Generator) DeclareIndexAndNameVar(run []Value, typeName string)

DeclareIndexAndNameVar is the single-run version of declareIndexAndNameVars

func (*Generator) DeclareIndexAndNameVars

func (g *Generator) DeclareIndexAndNameVars(runs [][]Value, typeName string)

DeclareIndexAndNameVars declares the index slices and concatenated names strings representing the runs of values.

func (*Generator) DeclareNameVars

func (g *Generator) DeclareNameVars(runs [][]Value, typeName string, suffix string)

DeclareNameVars declares the concatenated names string representing all the values in the runs.

func (*Generator) FindEnumTypes

func (g *Generator) FindEnumTypes() error

FindEnumTypes goes through all of the types in the package and finds all integer (signed or unsigned) types labeled with enums:enum or enums:bitflag. It stores the resulting types in [Generator.Types].

func (*Generator) Format

func (g *Generator) Format() ([]byte, error)

Format returns the contents of the Generator's buffer ([Generator.Buf]) with gofmt applied.

func (*Generator) Generate

func (g *Generator) Generate() error

Generate produces the enum methods for the types stored in [Generator.Types].

func (*Generator) InspectForType

func (g *Generator) InspectForType(n ast.Node) (bool, error)

InspectForType looks at the given AST node and adds it to [Generator.Types] if it is marked with an appropriate comment directive. It returns whether the AST inspector should continue, and an error if there is one. It should only be called in ast.Inspect.

func (*Generator) ParsePackage

func (g *Generator) ParsePackage() error

ParsePackage parses the single package located in the configuration directory.

func (*Generator) PrefixValueNames

func (g *Generator) PrefixValueNames(values []Value)

PrefixValueNames adds the prefix specified in [Generator.Config.AddPrefix] to each name of the given values.

func (*Generator) PrintDescMap

func (g *Generator) PrintDescMap(runs [][]Value, typeName string)

PrintDescMap prints the map of values to descriptions

func (*Generator) PrintDescSlice

func (g *Generator) PrintDescSlice(runs [][]Value, typeName string)

PrintDescSlice prints the slice of descriptions

func (*Generator) PrintHeader

func (g *Generator) PrintHeader()

PrintHeader prints the header and package clause to the accumulated output

func (*Generator) PrintNamesSlice

func (g *Generator) PrintNamesSlice(runs [][]Value, typeName string, runsThreshold int)

PrintNamesSlice prints the slice of names

func (*Generator) PrintValueMap

func (g *Generator) PrintValueMap(runs [][]Value, typeName string, runsThreshold int)

PrintValueMap prints the map between name and value

func (*Generator) Printf

func (g *Generator) Printf(format string, args ...any)

Printf prints the formatted string to the accumulated output in [Generator.Buf]

func (*Generator) TransformValueNames

func (g *Generator) TransformValueNames(values []Value)

TransformValueNames transforms the names of the given values according to the transform method specified in [Generator.Config.Transform]

func (*Generator) TrimValueNames

func (g *Generator) TrimValueNames(values []Value)

TrimValueNames removes the prefixes specified in [Generator.Config.TrimPrefix] from each name of the given values.

func (*Generator) Write

func (g *Generator) Write() error

Write formats the data in the the Generator's buffer ([Generator.Buf]) and writes it to the file specified by [Generator.Config.Output].

type Package

type Package struct {
	Dir      string
	Name     string
	Defs     map[*ast.Ident]types.Object
	Files    []*File
	TypesPkg *types.Package
}

Package holds information about a Go package

type Type

type Type struct {
	Type      *ast.TypeSpec // The standard AST type value
	IsBitFlag bool          // Whether the type is a bit flag type
}

Type represents a parsed enum type.

type Value

type Value struct {
	OriginalName string // The name of the constant before transformation
	Name         string // The name of the constant after transformation (i.e. camel case => snake case)
	Desc         string // The comment description of the constant
	// The Value is stored as a bit pattern alone. The boolean tells us
	// whether to interpret it as an int64 or a uint64; the only place
	// this matters is when sorting.
	// Much of the time the str field is all we need; it is printed
	// by Value.String.
	Value  uint64 // Will be converted to int64 when needed.
	Signed bool   // Whether the constant is a signed type.
	Str    string // The string representation given by the "go/constant" package.
}

Value represents a declared constant.

func (*Value) String

func (v *Value) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL