ygen

package
v0.29.19 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2024 License: Apache-2.0 Imports: 16 Imported by: 24

Documentation

Overview

Package ygen contains a library and base configuration options that can be extended to generate language-specific structs from a YANG model. The Goyang parsing library is used to parse YANG. The output can consider OpenConfig-specific conventions such that the schema is compressed. The output of this library is an intermediate representation (IR) designed to reduce the need for working with the Goyang parsing library's AST.

Index

Constants

View Source
const (
	// EnumeratedUnionSuffix is the type name suffix given to enumerations
	// defined as part of a union type.
	EnumeratedUnionSuffix = "Enum"
)

Variables

This section is empty.

Functions

func BytesToGoByteSlice

func BytesToGoByteSlice(b []byte) []string

BytesToGoByteSlice takes an input slice of bytes and outputs it as a slice of strings corresponding to lines of Go source code that define the byte slice. Each string within the slice contains up to 16 bytes of the output byte array, with each byte represented as a two digit hex character.

func FindSchemaPath added in v0.7.0

func FindSchemaPath(parent *Directory, fieldName string, absolutePaths bool) ([]string, error)

FindSchemaPath finds the relative or absolute schema path of a given field of a Directory. The Field is specified as a name in order to guarantee its existence before processing.

func FindShadowSchemaPath added in v0.18.0

func FindShadowSchemaPath(parent *Directory, fieldName string, absolutePaths bool) ([]string, error)

FindShadowSchemaPath finds the relative or absolute schema path of a given field of a Directory with preference to the shadow path. The Field is specified as a name in order to guarantee its existence before processing. NOTE: No error is returned if fieldName is not found.

func GetOrderedDirectories added in v0.7.0

func GetOrderedDirectories(directory map[string]*Directory) ([]string, map[string]*Directory, error)

GetOrderedDirectories returns an alphabetically-ordered slice of Directory names and a map of Directories keyed by their names instead of their paths, so that each directory can be processed in alphabetical order. This helps produce deterministic generated code, and minimize diffs when compared with expected output (i.e., diffs don't appear simply due to reordering of the Directory maps). If the names of the directories are not unique, which is unexpected, an error is returned. TODO(wenbli): Deprecate this after ygot uses the IR for code generation. This function's purpose is to check for name conflicts. This functionality doesn't belong during IR processing but rather with downstream language-specific processing since it's possible that conflicts are allowed (e.g. nested struct definitions).

func GetOrderedFieldNames added in v0.7.0

func GetOrderedFieldNames(directory *Directory) []string

GetOrderedFieldNames returns the field names of a Directory in alphabetical order.

func GetOrderedPathDirectories added in v0.18.1

func GetOrderedPathDirectories(directory map[string]*Directory) []string

GetOrderedPathDirectories returns an alphabetically-ordered slice of Directory names and a map of Directories keyed by their paths, so that each directory can be processed in path-alphabetical order. This helps produce deterministic generated code, and minimize diffs when compared with expected output (i.e., diffs don't appear simply due to reordering of the Directory maps).

func GoFieldNameMap added in v0.7.0

func GoFieldNameMap(directory *ParsedDirectory) map[string]string

GoFieldNameMap returns a map containing the Go name for a field (key is the field schema name). Name Uniquification is done to ensure compilation -- this is done deterministically.

func IsYgenDefinedGoType added in v0.7.0

func IsYgenDefinedGoType(t *MappedType) bool

IsYgenDefinedGoType returns true if the native type of a MappedType is a Go type that's defined by ygen's generated code.

func MakeFakeRoot added in v0.7.0

func MakeFakeRoot(rootName string) *yang.Entry

MakeFakeRoot creates and returns a fakeroot *yang.Entry with rootName as its name. It has an empty, but initialized Dir.

func WriteGzippedByteSlice

func WriteGzippedByteSlice(b []byte) ([]byte, error)

WriteGzippedByteSlice takes an input slice of bytes, gzips it and returns the resulting compressed output as a byte slice.

Types

type DirType added in v0.8.4

type DirType int64

DirType describes the different types of Directory that can be output within the IR such that 'list' directories can have special handling applied.

const (

	// Container represents a YANG 'container'.
	Container DirType
	// List represents a YANG 'list' that is 'ordered-by system'.
	List
	// OrderedList represents a YANG 'list' that is 'ordered-by user'.
	OrderedList
)

type Directory added in v0.7.0

type Directory struct {
	Name           string                 // Name is the name of the struct to be generated.
	Entry          *yang.Entry            // Entry is the yang.Entry that corresponds to the schema element being converted to a struct.
	Fields         map[string]*yang.Entry // Fields is a map, keyed by the YANG node identifier, of the entries that are the struct fields.
	ShadowedFields map[string]*yang.Entry // ShadowedFields is a map, keyed by the YANG node identifier, of the field entries duplicated via compression.
	Path           []string               // Path is a slice of strings indicating the element's path.
	ListAttr       *YangListAttr          // ListAttr is used to store characteristics of structs that represent YANG lists.
	IsFakeRoot     bool                   // IsFakeRoot indicates that the struct is a fake root struct, so specific mapping rules should be implemented.
}

Directory stores information needed for outputting a data node of the generated code. When viewed as a collection of entries that is generated from an entire YANG schema, they serve the purpose of mapping the YANG schema tree to a directory tree (connected through implicit yang.Entry edges) where each directory corresponds to a data node of the Go version of the schema, and where digested data is stored that is friendly to the code generation algorithm.

type EnumeratedValueType added in v0.8.4

type EnumeratedValueType int64

EnumeratedValueType is used to indicate the source YANG type that an enumeration was generated based on.

const (
	UnknownEnumerationType EnumeratedValueType = iota
	// SimpleEnumerationType represents 'enumeration' leaves within
	// the YANG schema that are defined inline.
	SimpleEnumerationType
	// DerivedEnumerationType represents enumerations that are defined
	// within a YANG 'typedef'.
	DerivedEnumerationType
	// UnionEnumerationType represents a 'type enumeration' defined within
	// a union.
	UnionEnumerationType
	// DerivedUnionEnumerationType represents a 'enumeration' defined
	// within a union that is itself within a typedef.
	DerivedUnionEnumerationType
	// IdentityType represents an enumeration that is an 'identity'
	// within the YANG schema.
	IdentityType
)

func (EnumeratedValueType) String added in v0.21.0

func (n EnumeratedValueType) String() string

type EnumeratedYANGType added in v0.8.4

type EnumeratedYANGType struct {
	// Name is the name of the generated enumeration to be
	// used in the generated code.
	Name string
	// Kind indicates the type of enumerated value that the
	// EnumeratedYANGType represents - allowing for a code
	// generation mechanism to select how different enumerated
	// value types are output.
	Kind EnumeratedValueType
	// IdentityBaseName, which is present only when the enumerated type is
	// an IdentityType, is the name of the base identity from which all
	// valid identity values are derived.
	IdentityBaseName string
	// TypeName stores the original YANG type name for the enumeration.
	TypeName string
	// TypeDefaultValue stores the default value of the enum type's default
	// statement (note: this is different from the default statement of the
	// leaf type).
	TypeDefaultValue string
	// ValToYANGDetails stores the YANG-ordered set of enumeration value
	// and its YANG-specific details (as defined by the
	// ygot.EnumDefinition).
	ValToYANGDetails []ygot.EnumDefinition
	// Flags contains extra information that can be populated by the
	// LangMapper during IR generation to assist the code generation stage.
	// Specifically, this field is set by the
	// LangMapperExt.PopulateEnumFlags function.
	Flags map[string]string
}

EnumeratedYANGType is an abstract representation of an enumerated type to be produced in the output code.

type IR added in v0.8.4

type IR struct {
	// Directories is the set of 'directory', or non-leaf entries that are
	// to be produced in the generated code. They are keyed by the absolute
	// YANG path of their locations.
	Directories map[string]*ParsedDirectory

	// Enums is the set of enumerated entries that are to be output in the
	// generated language code. They are each keyed by a name that
	// uniquely identifies the enumeration. Note that this name may not be
	// the same type name that would be used in the generated code due to
	// inner definitions.
	Enums map[string]*EnumeratedYANGType

	// ModelData stores the metadata extracted from the input YANG modules.
	ModelData []*gpb.ModelData
	// contains filtered or unexported fields
}

IR represents the returned intermediate representation produced by ygen to be consumed by language-specific passes prior to code generation.

func GenerateIR added in v0.8.4

func GenerateIR(yangFiles, includePaths []string, langMapper LangMapper, opts IROptions) (*IR, error)

GenerateIR creates the ygen intermediate representation for a set of YANG modules. The YANG files to be parsed are read from the yangFiles argument, with any includes that they use searched for in the string slice of paths specified by includePaths. The supplier LangMapper interface is used to perform mapping of language-specific naming whilst creating the IR -- the full details of the implementation of LangMapper can be found in ygen/ir.go and docs/code-generation-design.md.

The supplied IROptions controls the parsing and transformations that are applied to the schema whilst generating the IR.

GenerateIR returns the complete ygen intermediate representation.

func (*IR) OrderedDirectoryPaths added in v0.19.0

func (ir *IR) OrderedDirectoryPaths() []string

OrderedDirectoryPaths returns the absolute YANG paths of all ParsedDirectory entries in the IR in lexicographical order.

func (*IR) OrderedDirectoryPathsByName added in v0.19.0

func (ir *IR) OrderedDirectoryPathsByName() []string

OrderedDirectoryPathsByName returns the absolute YANG paths of all ParsedDirectory entries in the IR in the lexicographical order of their candidate generated names. Where there are duplicate names the path is used to tie-break.

func (*IR) SchemaTree added in v0.19.0

func (ir *IR) SchemaTree(inclDescriptions bool) ([]byte, error)

SchemaTree returns a JSON serialised tree of the schema for the set of modules used to generate the IR. The JSON document that is returned is always rooted on a yang.Entry which corresponds to the root item, and stores all root-level enties (and their subtrees) within the input module set. All YANG directories are annotated in the output JSON with the name of the type they correspond to in the generated code, and the absolute schema path that the entry corresponds to. In the case that there is not a fake root struct, a synthetic root entry is used to store the schema tree.

type IROptions added in v0.8.4

type IROptions struct {
	// ParseOptions specifies the options for how the YANG schema is
	// produced.
	ParseOptions ParseOpts

	// Transformation options specifies any transformations that should
	// be applied to the input YANG schema when producing the IR.
	TransformationOptions TransformationOpts

	// NestedDirectories specifies whether the generated directories should
	// be nested in the IR.
	NestedDirectories bool

	// AbsoluteMapPaths specifies whether the path annotation provided for
	// each field should be relative paths or absolute paths.
	AbsoluteMapPaths bool

	// AppendEnumSuffixForSimpleUnionEnums appends an "Enum" suffix to the
	// enumeration name for simple (i.e. non-typedef) leaves which are
	// unions with an enumeration inside. This makes all inlined
	// enumerations within unions, whether typedef or not, have this
	// suffix, achieving consistency. Since this flag is planned to be a
	// v1 compatibility flag along with
	// UseDefiningModuleForTypedefEnumNames, and will be removed in v1, it
	// only applies when useDefiningModuleForTypedefEnumNames is also set
	// to true.
	// NOTE: This flag will be removed by v1 release.
	AppendEnumSuffixForSimpleUnionEnums bool
}

IROptions contains options used to customize IR generation.

type LangMapper added in v0.8.4

type LangMapper interface {
	// LangMapperBaseSetup defines setup methods that are required for all
	// LangMapper instances.
	LangMapperBaseSetup

	// FieldName maps an input yang.Entry to the name that should be used
	// in the intermediate representation. It is called for each field of
	// a defined directory.
	FieldName(e *yang.Entry) (string, error)

	// DirectoryName maps an input yang.Entry to the name that should be used in the
	// intermediate representation (IR). It is called for any directory entity that
	// is to be output in the generated code.
	DirectoryName(*yang.Entry, genutil.CompressBehaviour) (string, error)

	// KeyLeafType maps an input yang.Entry which must represent a leaf to the
	// type that should be used when the leaf is used in the context of a
	// list key within the output IR.
	KeyLeafType(*yang.Entry, IROptions) (*MappedType, error)

	// LeafType maps an input yang.Entry which must represent a leaf to the
	// type that should be used when the leaf is used in the context of a
	// field within a directory within the output IR.
	LeafType(*yang.Entry, IROptions) (*MappedType, error)

	// PackageName maps an input yang.Entry, which must correspond to a
	// directory type (container or list), to the package name to which it
	// belongs. The bool parameter specifies whether the generated
	// directories will be nested or not since some languages allow nested
	// structs.
	PackageName(*yang.Entry, genutil.CompressBehaviour, bool) (string, error)

	// LangMapperExt contains extensions that the LangMapper instance
	// should implement if extra information from the IR is required.
	// When implementing this, UnimplementedLangMapperExt should be
	// embedded in the implementation type in order to ensure forward
	// compatibility.
	LangMapperExt
}

LangMapper is the interface to be implemented by a language-specific library and provided as an input to the IR production phase of ygen.

Note: though the output names are meant to be usable within the output language, it may not be the final name used in the generated code, for example due to naming conflicts, which are better resolved in a later pass prior to code generation (see note below).

NB: LangMapper's methods should be idempotent, such that the order in which they're called and the number of times each is called per input parameter does not affect the output. Do not depend on the same order of method calls on langMapper by GenerateIR.

type LangMapperBase added in v0.23.0

type LangMapperBase struct {
	// contains filtered or unexported fields
}

LangMapperBase contains unexported base types and exported built-in methods that all LangMapper implementation instances should embed. These built-in methods are available for use anywhere in the LangMapper implementation instance.

func (*LangMapperBase) EnumName added in v0.23.0

func (b *LangMapperBase) EnumName(e *yang.Entry, compressPaths, noUnderscores, skipDedup, shortenEnumLeafNames, addEnumeratedUnionSuffix bool, enumOrgPrefixesToTrim []string) (string, string, error)

EnumName retrieves the type name of the input enum *yang.Entry that will be used in the generated code, which is the first returned value. The second value returned is a string key that uniquely identifies this enumerated value among all possible enumerated values in the input set of YANG files.

In testing contexts, this function requires InjectEnumSet to be called prior to being usable.

func (*LangMapperBase) EnumeratedTypedefTypeName added in v0.23.0

func (b *LangMapperBase) EnumeratedTypedefTypeName(yangType *yang.YangType, contextEntry *yang.Entry, prefix string, noUnderscores, useDefiningModuleForTypedefEnumNames bool) (string, string, bool, error)

EnumeratedTypedefTypeName retrieves the name of an enumerated typedef (i.e., a typedef which is either an identityref or an enumeration). The resolved name is prefixed with the prefix supplied. If the type that was supplied within the resolveTypeArgs struct is not a type definition which includes an enumerated type, the third returned value (boolean) will be false. The second value returned is a string key that uniquely identifies this enumerated value among all possible enumerated values in the input set of YANG files.

In testing contexts, this function requires InjectEnumSet to be called prior to being usable.

func (*LangMapperBase) IdentityrefBaseTypeFromIdentity added in v0.23.0

func (b *LangMapperBase) IdentityrefBaseTypeFromIdentity(i *yang.Identity) (string, string, error)

IdentityrefBaseTypeFromIdentity retrieves the generated type name of the input *yang.Identity. The first value returned is the defining module followed by the CamelCase-ified version of the identity's name. The second value returned is a string key that uniquely identifies this enumerated value among all possible enumerated values in the input set of YANG files.

In testing contexts, this function requires InjectEnumSet to be called prior to being usable.

func (*LangMapperBase) IdentityrefBaseTypeFromLeaf added in v0.23.0

func (b *LangMapperBase) IdentityrefBaseTypeFromLeaf(idr *yang.Entry) (string, string, error)

IdentityrefBaseTypeFromLeaf retrieves the mapped name of an identityref's base such that it can be used in generated code. The first value returned is the defining module name followed by the CamelCase-ified version of the base's name. The second value returned is a string key that uniquely identifies this enumerated value among all possible enumerated values in the input set of YANG files. This function wraps the identityrefBaseTypeFromIdentity function since it covers the common case that the caller is interested in determining the name from an identityref leaf, rather than directly from the identity.

In testing contexts, this function requires InjectEnumSet to be called prior to being usable.

func (*LangMapperBase) InjectEnumSet added in v0.23.0

func (s *LangMapperBase) InjectEnumSet(entries map[string]*yang.Entry, compressPaths, noUnderscores, skipEnumDedup, shortenEnumLeafNames, useDefiningModuleForTypedefEnumNames, appendEnumSuffixForSimpleUnionEnums bool, enumOrgPrefixesToTrim []string) error

InjectEnumSet is intended to be called by unit tests in order to set up the LangMapperBase such that generated enumeration/identity names can be looked up. It walks the input map of enumerated value leaves keyed by path and creates generates names for them. The input parameters correspond to fields in IROptions. It returns an error if there is a failure to generate the enumerated values' names.

func (*LangMapperBase) InjectSchemaTree added in v0.23.0

func (s *LangMapperBase) InjectSchemaTree(entries []*yang.Entry) error

InjectSchemaTree is intended to be called by unit tests in order to set up the LangMapperBase such that leafrefs targets may be looked up. It maps a set of yang.Entry pointers into a ctree structure. It returns an error if there is duplication within the set of entries.

func (*LangMapperBase) ResolveLeafrefTarget added in v0.23.0

func (b *LangMapperBase) ResolveLeafrefTarget(path string, contextEntry *yang.Entry) (*yang.Entry, error)

ResolveLeafrefTarget takes an input path and context entry and determines the type of the leaf that is referred to by the path, such that it can be mapped to a native language type. It returns the yang.YangType that is associated with the target, and the target yang.Entry, such that the caller can map this to the relevant language type.

In testing contexts, this function requires InjectSchemaTree to be called prior to being usable.

type LangMapperBaseSetup added in v0.23.0

type LangMapperBaseSetup interface {

	// InjectEnumSet is intended to be called by unit tests in order to set up the
	// LangMapperBase such that generated enumeration/identity names can be looked
	// up. The input parameters correspond to fields in IROptions.
	// It returns an error if there is a failure to generate the enumerated
	// values' names.
	InjectEnumSet(entries map[string]*yang.Entry, compressPaths, noUnderscores, skipEnumDedup, shortenEnumLeafNames, useDefiningModuleForTypedefEnumNames, appendEnumSuffixForSimpleUnionEnums bool, enumOrgPrefixesToTrim []string) error

	// InjectSchemaTree is intended to be called by unit tests in order to set up
	// the LangMapperBase such that leafrefs targets may be looked up.
	// It returns an error if there is duplication within the set of entries.
	InjectSchemaTree(entries []*yang.Entry) error
	// contains filtered or unexported methods
}

LangMapperBaseSetup defines setup methods that are required for all LangMapper instances.

type LangMapperExt added in v0.23.0

type LangMapperExt interface {
	// PopulateFieldFlags populates extra information given a particular
	// field of a ParsedDirectory and the corresponding AST node.
	// Fields of a ParsedDirectory can be any non-choice/case node (e.g.
	// YANG leafs, containers, lists).
	PopulateFieldFlags(NodeDetails, *yang.Entry) map[string]string
	// PopulateEnumFlags populates extra information given a particular
	// enumerated type its corresponding AST representation.
	PopulateEnumFlags(EnumeratedYANGType, *yang.YangType) map[string]string
}

LangMapperExt contains extensions that the LangMapper instance should implement if extra information from the IR is required. These flag values are expected to contain information rarely used but needed from goyang's AST. Values that are expected to be used more often should be placed in the IR itself so that other users can get access to the same information without implementing it themselves.

type ListKey added in v0.18.1

type ListKey struct {
	// Name is the candidate language-specific name of the list key leaf.
	Name string
	// LangType describes the type that the node should be given in
	// the output code, using the output of the language-specific
	// type mapping provided by calling the LangMapper interface.
	LangType *MappedType
}

type MappedType added in v0.7.0

type MappedType struct {
	// NativeType is the candidate language-specific type name which is to
	// be used for the mapped entity.
	NativeType string
	// UnionTypes is a map, keyed by the generated type name (NativeType of
	// the subtype), of information about each union subtype.
	UnionTypes map[string]MappedUnionSubtype
	// IsEnumeratedValue specifies whether the NativeType that is returned
	// is a generated enumerated value. Such entities are reflected as
	// derived types with constant values, and are hence not represented
	// as pointers in the output code.
	IsEnumeratedValue bool
	// EnumeratedYANGTypeKey stores a globally-unique key that can be
	// used to key into IR's EnumeratedYANGTypes map containing all of the
	// enumeration definitions. This value should only be populated when
	// IsEnumeratedValue is true.
	EnumeratedYANGTypeKey string
	// ZeroValue stores the value that should be used for the type if
	// it is unset. This is used only in contexts where the nil pointer
	// cannot be used, such as leaf getters.
	ZeroValue string
	// DefaultValue stores the default value for the type if is specified.
	// It is represented as a string pointer to ensure that default values
	// of the empty string can be distinguished from unset defaults.
	DefaultValue *string
}

MappedType is used to store the generated language type that a leaf entity in YANG is mapped to. The NativeType is always populated for any leaf. UnionTypes is populated when the type may have subtypes (i.e., is a union). enumValues is populated when the type is an enumerated type.

The code generation explicitly maps YANG types to corresponding generated language types. In the case that an explicit mapping is not specified, a type will be mapped to an empty interface (interface{}). For an explicit list of types that are supported, see the yangTypeTo*Type functions in this package.

func (*MappedType) OrderedUnionTypes added in v0.8.11

func (t *MappedType) OrderedUnionTypes() []string

OrderedUnionTypes returns a slice of union type names of the given MappedType in YANG order. If the type is not a union (i.e. UnionTypes is empty), then a nil slice is returned.

type MappedUnionSubtype added in v0.21.0

type MappedUnionSubtype struct {
	// Index, which starts from 0, indicates the order of the subtype
	// within the union definition, since order is important for unions in
	// YANG.
	// Where two types are mapped to the same generated language type
	// (e.g., string) then only the order of the first is maintained. Since
	// the generated code from the structs maintains only type validation,
	// this is not currently a limitation.
	Index int
	// EnumeratedYANGTypeKey stores a globally-unique key that can be
	// used to key into IR's EnumeratedYANGTypes map containing all of the
	// enumeration definitions. This value should only be populated when
	// the union subtype is an enumerated type.
	EnumeratedYANGTypeKey string
}

MappedUnionSubtype stores information associated with a union subtype within a MappedType.

type NodeDetails added in v0.8.4

type NodeDetails struct {
	// Name is the language-specific name that should be used for
	// the node.
	Name string
	// YANGDetails stores details of the node from the original
	// YANG schema, such that some characteristics can be accessed
	// by the code generation process. Only details that are
	// directly required are provided.
	YANGDetails YANGNodeDetails
	// Type describes the type of node that the leaf represents,
	// allowing for container, list, leaf and leaf-list entries
	// to be distinguished.
	// In the future it can be used to store other node types that
	// form a direct child of a subtree node.
	Type NodeType
	// LangType describes the type that the node should be given in
	// the output code, using the output of the language-specific
	// type mapping provided by calling the LangMapper interface.
	LangType *MappedType
	// MappedPaths describes the paths that the output node should
	// be mapped to in the output code - these annotations can be
	// used to annotation the output code with the field(s) that it
	// corresponds to in the YANG schema.
	MappedPaths [][]string
	// MappedPathModules describes the path elements' belonging modules that
	// the output node should be mapped to in the output code - these
	// annotations can be used to annotation the output code with the
	// field(s) that it corresponds to in the YANG schema.
	MappedPathModules [][]string
	// ShadowMappedPaths describes the shadow paths (if any) that the output
	// node should be mapped to in the output code - these annotations can
	// be used to annotation the output code with the field(s) that it
	// corresponds to in the YANG schema.
	// Shadow paths are paths that have sibling config/state values
	// that have been compressed out due to path compression.
	ShadowMappedPaths [][]string
	// ShadowMappedPathModules describes the shadow path elements' belonging
	// modules (if any) that the output node should be mapped to in the
	// output code - these annotations can be used to annotation the output
	// code with the field(s) that it corresponds to in the YANG schema.
	// Shadow paths are paths that have sibling config/state values
	// that have been compressed out due to path compression.
	ShadowMappedPathModules [][]string
	// Flags contains extra information that can be populated by the
	// LangMapper during IR generation to assist the code generation stage.
	// Specifically, this field is set by the
	// LangMapperExt.PopulateFieldFlags function.
	Flags map[string]string
}

NodeDetails describes an individual field of the generated code tree. The Node may correspond to another Directory entry in the output code, or a individual leaf node.

type NodeType added in v0.8.4

type NodeType int64

NodeType describes the different types of node that can be output within the IR.

const (
	// InvalidNode represents a node that has not been correctly
	// set up.
	InvalidNode NodeType = iota
	// ContainerNode indicates a YANG 'container'.
	ContainerNode
	// ListNode indicates a YANG 'list'.
	ListNode
	// LeafNode represents a YANG 'leaf'.
	LeafNode
	// LeafListNode represents a YANG 'leaf-list'.
	LeafListNode
	// AnyDataNode represents a YANG 'anydata'.
	AnyDataNode
)

func (NodeType) String added in v0.19.0

func (n NodeType) String() string

type ParseOpts added in v0.7.0

type ParseOpts struct {
	// IgnoreUnsupportedStatements ignores unsupported YANG statements when
	// parsing, such that they do not show up errors during IR generation.
	IgnoreUnsupportedStatements bool
	// ExcludeModules specifies any modules that are included within the set of
	// modules that should have code generated for them that should be ignored during
	// code generation. This is due to the fact that some schemas (e.g., OpenConfig
	// interfaces) currently result in overlapping entities (e.g., /interfaces).
	ExcludeModules []string
	// YANGParseOptions provides the options that should be handed to the
	// github.com/openconfig/goyang/pkg/yang library. These specify how the
	// input YANG files should be parsed.
	YANGParseOptions yang.Options
}

ParseOpts contains parsing configuration for a given schema.

type ParsedDirectory added in v0.8.4

type ParsedDirectory struct {
	// Name is the candidate language-specific name of the directory.
	Name string
	// Type describes the type of directory that is being produced -
	// such that YANG 'list' entries can have special handling.
	Type DirType
	// Path specifies the absolute YANG schema path of the node.
	Path string
	// SchemaPath specifies the absolute YANG schema node path. It does not
	// include the module name nor choice/case elements in the YANG file.
	SchemaPath string
	// Fields is the set of direct children of the node that are to be
	// output. It is keyed by the YANG node identifier of the child field
	// since there could be name conflicts at this processing stage.
	Fields map[string]*NodeDetails
	// ListKeys describes the leaves of a YANG list that
	// are required in the output code (e.g., the characteristics
	// of the list's keys). It is keyed by the YANG name of the list key.
	ListKeys map[string]*ListKey
	// ListKeyYANGNames is the ordered list of YANG names specified in the
	// YANG list per Section 7.8.2 of RFC6020. The consumer of the IR can
	// rely on this ordering for deterministic ordering in output code and
	// rendering.
	ListKeyYANGNames []string
	// PackageName is the package in which this directory node's generated
	// code should reside.
	PackageName string
	// IsFakeRoot indicates whether the directory being described
	// is the root entity and has been synthetically generated by
	// ygen.
	IsFakeRoot bool
	// BelongingModule is the name of the module having the same XML
	// namespace as this directory node.
	// For more information on YANG's XML namespaces see
	// https://datatracker.ietf.org/doc/html/rfc7950#section-5.3
	BelongingModule string
	// RootElementModule is the module in which the root of the YANG tree that the
	// node is attached to was instantiated (rather than the module that
	// has the same namespace as the node).
	//
	// In this example, container 'con' has
	// RootElementModule: "openconfig-simple"
	// BelongingModule:   "openconfig-augment"
	// DefiningModule:    "openconfig-grouping"
	//
	//   module openconfig-augment {
	//     import openconfig-simple { prefix "s"; }
	//     import openconfig-grouping { prefix "g"; }
	//
	//     augment "/s:parent/child/state" {
	//       uses g:group;
	//     }
	//   }
	//
	//   module openconfig-grouping {
	//     grouping group {
	//       container con {
	//         leaf zero { type string; }
	//       }
	//     }
	//   }
	RootElementModule string
	// DefiningModule is the module that contains the text definition of
	// the field.
	DefiningModule string
	// ConfigFalse represents whether the node is state data as opposed to
	// configuration data.
	// The meaning of "config" is exactly the same as the "config"
	// statement in YANG:
	// https://datatracker.ietf.org/doc/html/rfc7950#section-7.21.1
	ConfigFalse bool
	// TelemetryAtomic indicates that the node has been modified with the
	// OpenConfig extension "telemetry-atomic".
	// https://github.com/openconfig/public/blob/master/release/models/openconfig-extensions.yang#L154
	//
	// For example in the relative path /subinterfaces/subinterface, this
	// field be true if and only if the second element, /interface, is
	// marked "telemetry-atomic" in the YANG schema.
	TelemetryAtomic bool
	// CompressedTelemetryAtomic indicates that a parent of the node which
	// has been compressed out has been modified with the OpenConfig
	// extension "telemetry-atomic".
	//
	// For example, /interfaces/interface/subinterfaces/subinterface may be
	// a path where the /subinterfaces element within the relative path
	// /subinterfaces/subinterface is marked "telemetry-atomic". In this
	// case, this field will be marked true since the relative path from
	// the parent ParsedDirectory contains a compressed-out element that's
	// marked "telemetry-atomic".
	//
	// https://github.com/openconfig/public/blob/master/release/models/openconfig-extensions.yang#L154
	CompressedTelemetryAtomic bool
}

ParsedDirectory describes an internal node within the generated code. Such a 'directory' may represent a struct, or a message, in the generated code. It represents a YANG 'container' or 'list'.

func (*ParsedDirectory) ChildDirectories added in v0.21.0

func (d *ParsedDirectory) ChildDirectories(ir *IR) ([]*ParsedDirectory, error)

OrderedFieldNames returns the YANG name of all child directories for ParsedDirectory in lexicographical order. It returns an error if any child directory field doesn't exist in the input IR.

func (*ParsedDirectory) OrderedFieldNames added in v0.19.0

func (d *ParsedDirectory) OrderedFieldNames() []string

OrderedFieldNames returns the YANG name of all fields belonging to the ParsedDirectory in lexicographical order.

func (*ParsedDirectory) OrderedListKeyNames added in v0.21.0

func (d *ParsedDirectory) OrderedListKeyNames() []string

OrderedFieldNames returns the YANG name of all key fields belonging to the ParsedDirectory in lexicographical order.

type TransformationOpts added in v0.7.0

type TransformationOpts struct {
	// CompressBehaviour specifies how the set of direct children of any
	// entry should determined. Specifically, whether compression is
	// enabled, and whether state fields in the schema should be excluded.
	CompressBehaviour genutil.CompressBehaviour
	// GenerateFakeRoot specifies whether an entity that represents the
	// root of the YANG schema tree should be generated in the generated
	// code.
	GenerateFakeRoot bool
	// FakeRootName specifies the name of the struct that should be generated
	// representing the root.
	FakeRootName string
	// ExcludeState specifies whether config false values should be
	// included in the generated code output. When set, all values that are
	// not writeable (i.e., config false) within the YANG schema and their
	// children are excluded from the generated code.
	ExcludeState bool
	// SkipEnumDeduplication specifies whether leaves of type 'enumeration' that
	// are used in multiple places in the schema should share a common type within
	// the generated code that is output by ygen. By default (false), a common type
	// is used.
	//
	// This behaviour is useful in scenarios where there is no difference between
	// two types, and the leaf is mirrored in a logical way (e.g., the OpenConfig
	// config/state split). For example:
	//
	// grouping foo-config {
	//	leaf enabled {
	//		type enumeration {
	//			enum A;
	//			enum B;
	//			enum C;
	//		}
	//	 }
	// }
	//
	//  container config { uses foo-config; }
	//  container state { uses foo-config; }
	//
	// will result in a single enumeration type (ModuleName_Config_Enabled) being
	// output when de-duplication is enabled.
	//
	// When it is disabled, two different enumerations (ModuleName_(State|Config)_Enabled)
	// will be output in the generated code.
	SkipEnumDeduplication bool
	// ShortenEnumLeafNames removes the module name from the name of
	// enumeration leaves.
	ShortenEnumLeafNames bool
	// EnumOrgPrefixesToTrim trims the organization name from the module
	// part of the name of enumeration leaves if there is a match.
	EnumOrgPrefixesToTrim []string
	// UseDefiningModuleForTypedefEnumNames uses the defining module name
	// to prefix typedef enumerated types instead of the module where the
	// typedef enumerated value is used.
	UseDefiningModuleForTypedefEnumNames bool
	// EnumerationsUseUnderscores specifies whether enumeration names
	// should use underscores between path segments.
	EnumerationsUseUnderscores bool
}

TransformationOpts specifies transformations to the generated code with respect to the input schema.

type UnimplementedLangMapperExt added in v0.23.0

type UnimplementedLangMapperExt struct {
}

UnimplementedLangMapperExt should be embedded to have forward compatible implementations.

func (UnimplementedLangMapperExt) PopulateEnumFlags added in v0.23.0

PopulateEnumFlags populates extra information given a particular enumerated type its corresponding AST representation.

func (UnimplementedLangMapperExt) PopulateFieldFlags added in v0.23.0

func (UnimplementedLangMapperExt) PopulateFieldFlags(NodeDetails, *yang.Entry) map[string]string

PopulateFieldFlags populates extra information given a particular field of a ParsedDirectory and the corresponding AST node.

type YANGNodeDetails added in v0.8.4

type YANGNodeDetails struct {
	// Name is the name of the node from the YANG schema.
	Name string
	// Defaults represents the 'default' value(s) directly
	// specified in the YANG schema.
	Defaults []string
	// BelongingModule is the name of the module having the same XML
	// namespace as this node.
	// For more information on YANG's XML namespaces see
	// https://datatracker.ietf.org/doc/html/rfc7950#section-5.3
	BelongingModule string
	// RootElementModule is the module in which the root of the YANG tree that the
	// node is attached to was instantiated (rather than the module that
	// has the same namespace as the node).
	//
	// In this example, leaf 'zero' has
	// RootElementModule: "openconfig-simple"
	// BelongingModule:   "openconfig-augment"
	// DefiningModule:    "openconfig-grouping"
	//
	//   module openconfig-augment {
	//     import openconfig-simple { prefix "s"; }
	//     import openconfig-grouping { prefix "g"; }
	//
	//     augment "/s:parent/child/state" {
	//       uses g:group;
	//     }
	//   }
	//
	//   module openconfig-grouping {
	//     grouping group {
	//       leaf zero { type string; }
	//     }
	//   }
	RootElementModule string
	// DefiningModule is the module that contains the text definition of
	// the field.
	DefiningModule string
	// Path specifies the absolute YANG schema node path that can be used
	// to index into the ParsedDirectory map in the IR. It includes the
	// module name as well as choice/case elements.
	Path string
	// SchemaPath specifies the absolute YANG schema node path. It does not
	// include the module name nor choice/case elements in the YANG file.
	SchemaPath string
	// ShadowSchemaPath, which specifies the absolute YANG schema node path
	// of the "shadowed" sibling node, is included when a leaf exists in
	// both 'intended' and 'applied' state of an OpenConfig schema (see
	// https://datatracker.ietf.org/doc/html/draft-openconfig-netmod-opstate-01)
	// and hence is within the 'config' and 'state' containers of the
	// schema. ShadowSchemaPath is populated only when the -compress
	// generator flag is used, and indicates the path of the node not
	// represented in the generated IR based on the preference to prefer
	// intended or applied leaves.
	// Similar to SchemaPath, it does not include the module name nor
	// choice/case elements.
	ShadowSchemaPath string
	// LeafrefTargetPath is the absolute YANG schema node path of the
	// target node to which the leafref points via its path statement. Note
	// that this is *not* the recursively-resolved path.
	// This is populated only if the YANG node was a leafref.
	LeafrefTargetPath string
	// PresenceStatement, if non-nil, indicates that this directory is a
	// presence container. It contains the value of the presence statement.
	PresenceStatement *string
	// Description contains the description of the node.
	Description string
	// OrderedByUser indicates whether the node has the modifier
	// "ordered-by user".
	OrderedByUser bool
	// ConfigFalse represents whether the node is state data as opposed to
	// configuration data.
	// The meaning of "config" is exactly the same as the "config"
	// statement in YANG:
	// https://datatracker.ietf.org/doc/html/rfc7950#section-7.21.1
	ConfigFalse bool
}

YANGNodeDetails stores the YANG-specific details of a node within the schema. TODO(wenbli): Split this out so that parts can be re-used by ParsedDirectory.

type YangListAttr added in v0.7.0

type YangListAttr struct {
	// keys is a map, keyed by the name of the key leaf, with values of the type
	// of the key of a YANG list.
	Keys map[string]*ListKey
	// keyElems is a slice containing the pointers to yang.Entry structs that
	// make up the list key.
	KeyElems []*yang.Entry
	// ListKeyYANGNames is the ordered list of YANG names specified in the
	// YANG list per Section 7.8.2 of RFC6020. ygot relies on this ordering
	// for deterministic ordering in output code and rendering.
	ListKeyYANGNames []string
}

YangListAttr is used to store the additional elements for a Go struct that are required if the struct represents a YANG list. It stores the name of the key elements, and their associated types, along with pointers to those elements.

Directories

Path Synopsis
Package schematest is used for testing with the default OpenConfig generated structs.
Package schematest is used for testing with the default OpenConfig generated structs.

Jump to

Keyboard shortcuts

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