codegen

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: MIT Imports: 28 Imported by: 7

Documentation

Overview

Package codegen contains data structures and algorithms used by the Loom code generation tool.

In particular package codegen defines the data structure that represents a generated file (see File) which is composed of sections, each corresponding to a Go text template and accompanying data used to render the final code.

The package also includes functions that generate code to transform a given type into another (see GoTransform).

Index

Constants

View Source
const Gendir = "gen"

Gendir is the name of the subdirectory of the output directory that contains the generated files. This directory is wiped and re-written each time goa is run.

Variables

View Source
var DesignVersion = goa.Major

DesignVersion contains the major component of the version of Loom used to author the design. This value is initialized when the generated tool is invoked by retrieving the information passed on the command line by the loom tool.

Functions

func AddFileImport

func AddFileImport(file *File, imprts ...*ImportSpec)

AddFileImport adds imports to the first header section of the given file.

func AddImport

func AddImport(section *SectionTemplate, imprts ...*ImportSpec)

AddImport adds imports to a section template that was generated with Header.

func AddServiceMetaTypeImports

func AddServiceMetaTypeImports(header *SectionTemplate, svc *expr.ServiceExpr)

AddServiceMetaTypeImports adds meta type imports for each method of the service expr

func AttributeTags

func AttributeTags(_, att *expr.AttributeExpr) string

AttributeTags computes the struct field tags from its metadata if any.

func AttributeTagsWithName

func AttributeTagsWithName(parent *expr.AttributeExpr, fieldName string, att *expr.AttributeExpr) string

AttributeTagsWithName computes the struct field tags from its metadata, interpreting the "struct:tag:json:name" key when present.

The "struct:tag:json" meta key always takes precedence and is treated as a complete tag override value. When only "struct:tag:json:name" is set, Loom computes the json tag and appends ",omitempty" when the field is not required by its parent object. When no explicit JSON metadata is present, Loom emits a default json tag that preserves the DSL field name.

func AttributeValidationCode

func AttributeValidationCode(att *expr.AttributeExpr, put expr.UserType, attCtx *AttributeContext, req, alias bool, target, attName string) string

AttributeValidationCode produces Go code that runs the validations defined in the given attribute against the value held by the variable named target.

See ValidationCode for a description of the arguments.

func CamelCase

func CamelCase(name string, firstUpper, acronym bool) string

CamelCase produces the CamelCase version of the given string. It removes any non letter and non digit character.

If firstUpper is true the first letter of the string is capitalized else the first letter is in lowercase.

If acronym is true and a part of the string is a common acronym then it keeps the part capitalized (firstUpper = true) (e.g. APIVersion) or lowercase (firstUpper = false) (e.g. apiVersion).

func CommandLine

func CommandLine() string

CommandLine return the command used to run this process.

func Comment

func Comment(elems ...string) string

Comment produces line comments by concatenating the given strings and producing 80 characters long lines starting with "//".

func CommentBlock

func CommentBlock(stmt *jen.Statement, text string) *jen.Statement

CommentBlock appends a wrapped Go comment block line by line.

func CreateTempFile

func CreateTempFile(t *testing.T, content string) string

CreateTempFile creates a temporary file and writes the given content. It is used only for testing.

func Doc

func Doc(stmt *jen.Statement, text string) *jen.Statement

Doc appends a wrapped Go doc comment followed by a blank line.

func Expr

func Expr(code string) *jen.Statement

Expr renders a precomputed Go expression as-is.

func FormatTestCode

func FormatTestCode(t *testing.T, code string) string

FormatTestCode formats the given Go code. The code must correspond to the content of a valid Go source file (i.e. start with "package")

func GoNativeTypeName

func GoNativeTypeName(t expr.DataType) string

GoNativeTypeName returns the Go built-in type corresponding to the given primitive type. GoNativeType panics if t is not a primitive type.

func Goify

func Goify(str string, firstUpper bool) string

Goify makes a valid Go identifier out of any string. It does that by removing any non letter and non digit character and by making sure the first character is a letter or "_". Goify produces a "CamelCase" version of the string, if firstUpper is true the first character of the identifier is uppercase otherwise it's lowercase.

func GoifyAtt

func GoifyAtt(att *expr.AttributeExpr, name string, upper bool) string

GoifyAtt honors any struct:field:name meta set on the attribute and calls Goify with the tag value if present or the given name otherwise.

func Indent

func Indent(s, prefix string) string

Indent inserts prefix at the beginning of each non-empty line of s. The end-of-line marker is NL.

func IsCompatible

func IsCompatible(a, b expr.DataType, actx, bctx string) error

IsCompatible returns an error if a and b are not both objects, both arrays, both maps, both unions or one union and one object. actx and bctx are used to build the error message if any.

func JoinImportPath

func JoinImportPath(genpkg, rel string) string

JoinImportPath constructs a generated import path by joining the generation package root with a path relative to the generated `gen` tree.

func KebabCase

func KebabCase(name string) string

KebabCase produces the kebab-case version of the given CamelCase string.

func MapDepth

func MapDepth(m *expr.Map) int

MapDepth returns the level of nested maps. For unnested maps, it returns 0.

func RegisterPlugin

func RegisterPlugin(name string, cmd string, pre PrepareFunc, p GenerateFunc)

RegisterPlugin adds the plugin to the list of plugins to be invoked with the given command.

func RegisterPluginFirst

func RegisterPluginFirst(name string, cmd string, pre PrepareFunc, p GenerateFunc)

RegisterPluginFirst adds the plugin to the beginning of the list of plugins to be invoked with the given command. If more than one plugins are registered using this, the plugins will be sorted alphabetically by their names. If two plugins have same names, then they are sorted by registration order.

func RegisterPluginLast

func RegisterPluginLast(name string, cmd string, pre PrepareFunc, p GenerateFunc)

RegisterPluginLast adds the plugin to the end of the list of plugins to be invoked with the given command. If more than one plugins are registered using this, the plugins will be sorted alphabetically by their names. If two plugins have same names, then they are sorted by registration order.

func RunDSL

func RunDSL(t *testing.T, dsl func()) *expr.RootExpr

RunDSL returns the DSL root resulting from running the given DSL.

func RunPluginsPrepare

func RunPluginsPrepare(cmd, genpkg string, roots []eval.Root) error

RunPluginsPrepare executes the plugins prepare functions in the order they were registered.

func SectionCode

func SectionCode(t *testing.T, section Section) string

SectionCode generates and formats the code for the given section.

func SectionCodeFromImportsAndMethods

func SectionCodeFromImportsAndMethods(t *testing.T, importSection, methodSection Section) string

SectionCodeFromImportsAndMethods generates and formats the code for given import and method definition sections.

func SectionsCode

func SectionsCode(t *testing.T, sections []Section) string

SectionsCode generates and formats the code for the given sections.

func SnakeCase

func SnakeCase(name string) string

SnakeCase produces the snake_case version of the given CamelCase string. News => news OldNews => old_news CNNNews => cnn_news

func TemplateFuncs

func TemplateFuncs() map[string]any

TemplateFuncs lists common template helper functions.

func TypeRef

func TypeRef(ref string) *jen.Statement

TypeRef renders a precomputed Go type reference as-is.

func UnionValTypeName

func UnionValTypeName(unionName string) string

UnionValTypeName returns the Go type name of the interface and method used to type the union.

func ValidationCode

func ValidationCode(att *expr.AttributeExpr, put expr.UserType, attCtx *AttributeContext, req, alias, view bool, target string) string

ValidationCode produces Go code that runs the validations defined in the given attribute and its children recursively against the value held by the variable named target.

put is the parent UserType if any. It is used to compute proto oneof type names.

attCtx is the attribute context used to generate attribute name and reference in the validation code.

req indicates whether the attribute is required (true) or optional (false)

alias indicates whether the attribute is an alias user type attribute.

view indicates whether the attribute is a view type attribute. This only matters for union types: generated Loom view union types have a different layout than proto generated union types.

target is the variable name against which the validation code is generated

context is used to produce helpful messages in case of error.

func Walk

func Walk(a *expr.AttributeExpr, walker func(*expr.AttributeExpr) error) error

Walk traverses the data structure recursively and calls the given function once on each attribute starting with a.

func WalkMappedAttr

func WalkMappedAttr(ma *expr.MappedAttributeExpr, it MappedAttributeWalker) error

WalkMappedAttr iterates over the mapped attributes. It calls the given function giving each attribute as it iterates. WalkMappedAttr stops if there is no more attribute to iterate over or if the iterator function returns an error in which case it returns the error.

func WalkType

func WalkType(u expr.UserType, walker func(*expr.AttributeExpr) error) error

WalkType traverses the data structure recursively and calls the given function once on each attribute starting with the user type attribute.

func WrapText

func WrapText(text string, maxChars int) string

WrapText produces lines with text capped at maxChars it will keep words intact and respects newlines.

Types

type AttributeContext

type AttributeContext struct {
	// Pointer if true indicates that the attribute uses pointers to hold
	// primitive types even if they are required or has a default value.
	// It ignores UseDefault and IgnoreRequired properties.
	Pointer bool
	// IgnoreRequired if true indicates that the transport object
	// (proto) uses non-pointers to hold required attributes and
	// therefore do not need to be validated.
	IgnoreRequired bool
	// UseDefault if true indicates that the attribute uses non-pointers for
	// primitive types if they have default value. If false, the attribute with
	// primitive types are non-pointers if they are required, otherwise they
	// are pointers.
	UseDefault bool
	// Scope is the attribute scope.
	Scope Attributor
	// DefaultPkg is the default package name where the attribute
	// type is found. it can be overridden via struct:pkg:path meta.
	DefaultPkg string
	// IsInterface is true if the attribute is an interface (union type).
	// In this case assigning child attributes requires a type assertion.
	IsInterface bool
	// SamePackageConversion if true indicates that this context is being used
	// for conversion code generation within the same package as the types.
	SamePackageConversion bool
}

AttributeContext contains properties which impacts the code generating behavior of an attribute.

func NewAttributeContext

func NewAttributeContext(pointer, reqIgnore, useDefault bool, pkg string, scope *NameScope) *AttributeContext

NewAttributeContext initializes an attribute context.

func NewAttributeContextForConversion

func NewAttributeContextForConversion(pointer, reqIgnore, useDefault bool, pkg string, scope *NameScope) *AttributeContext

NewAttributeContextForConversion initializes an attribute context for same-package conversion.

func (*AttributeContext) Dup

Dup creates a shallow copy of the AttributeContext.

func (*AttributeContext) IsPrimitivePointer

func (a *AttributeContext) IsPrimitivePointer(name string, att *expr.AttributeExpr) bool

IsPrimitivePointer returns true if the attribute with the given name is a primitive pointer in the given parent attribute.

func (*AttributeContext) Pkg

Pkg returns the package name of the given type.

type AttributeScope

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

AttributeScope contains the scope of an attribute. It implements the Attributor interface.

func NewAttributeScope

func NewAttributeScope(scope *NameScope) *AttributeScope

NewAttributeScope initializes an attribute scope.

func (*AttributeScope) Field

func (*AttributeScope) Field(att *expr.AttributeExpr, name string, firstUpper bool) string

Field returns a valid Go struct field name.

func (*AttributeScope) Name

func (a *AttributeScope) Name(att *expr.AttributeExpr, pkg string, ptr, useDefault bool) string

Name returns the type name for the given attribute.

func (*AttributeScope) Ref

func (a *AttributeScope) Ref(att *expr.AttributeExpr, pkg string) string

Ref returns the type name for the given attribute.

func (*AttributeScope) Scope

func (a *AttributeScope) Scope() *NameScope

Scope returns the name scope.

type Attributor

type Attributor interface {
	Scoper
	// Name generates a valid name for the given attribute type. ptr and
	// useDefault are used to generate inline struct type definitions.
	Name(att *expr.AttributeExpr, pkg string, ptr, useDefault bool) string
	// Ref generates a valid reference to the given attribute type.
	Ref(att *expr.AttributeExpr, pkg string) string
	// Field generates a valid data structure field identifier for the given
	// attribute and field name. If firstUpper is true then the field name
	// first letter is capitalized.
	Field(att *expr.AttributeExpr, name string, firstUpper bool) string
}

Attributor defines the behavior of an attribute expression during code generation.

type File

type File struct {
	// Sections is the list of file sections in order of rendering. New
	// generator code should prefer this field over SectionTemplates.
	Sections []Section
	// SectionTemplates is the list of file section templates in
	// order of rendering.
	//
	// Deprecated: kept for compatibility while generators migrate to the
	// generic Section abstraction.
	SectionTemplates []*SectionTemplate
	// Path returns the file path relative to the output directory.
	Path string
	// SkipExist indicates whether the file should be skipped if one
	// already exists at the given path.
	SkipExist bool
	// FinalizeFunc is called after the file has been generated. It
	// is given the absolute path to the file as argument.
	FinalizeFunc func(string) error
}

A File contains the logic to generate a complete file.

func RunPlugins

func RunPlugins(cmd, genpkg string, roots []eval.Root, genfiles []*File) ([]*File, error)

RunPlugins executes the plugins registered with the given command in the order they were registered.

func VersionFile

func VersionFile() *File

VersionFile returns a file that contains the goa version used to generate the code. The file is written to gen/goa.json.

func (*File) AllSections

func (f *File) AllSections() []Section

AllSections returns all file sections using the generic section abstraction.

func (*File) HeaderTemplate

func (f *File) HeaderTemplate() *SectionTemplate

HeaderTemplate returns the first section when it is a template-backed header.

func (*File) Render

func (f *File) Render(dir string) (string, error)

Render executes the file section templates and writes the resulting bytes to an output file. The path of the output file is computed by appending the file path to dir. If a file already exists with the computed path then Render happens the smallest integer value greater than 1 to make it unique. Renders returns the computed path.

func (*File) Section

func (f *File) Section(name string) []Section

Section returns the sections with the given name or nil if not found.

func (*File) SetSections

func (f *File) SetSections(sections []Section)

SetSections replaces the file sections with the given generic section list.

type GenerateFunc

type GenerateFunc func(genpkg string, roots []eval.Root, files []*File) ([]*File, error)

GenerateFunc makes it possible to modify the files generated by the goa code generators and other plugins. A GenerateFunc accepts the Go import path of the "gen" package, the design roots as well as the currently generated files (produced initially by the goa generators and potentially modified by previously run plugins) and returns a new set of files.

type Hasher

type Hasher interface {
	// Hash computes a unique instance hash suitable for indexing
	// in a map.
	Hash() string
}

Hasher is the interface implemented by the objects that must be scoped.

type HeaderData

type HeaderData struct {
	Title   string
	Pkg     string
	Imports []*ImportSpec
}

HeaderData contains the typed data needed to render a generated Go file header.

func HeaderSectionData

func HeaderSectionData(section *SectionTemplate) *HeaderData

HeaderSectionData returns the typed header data if the section is a generated header.

type ImportSpec

type ImportSpec struct {
	// Name of imported package if needed.
	Name string
	// Go import path of package.
	Path string
}

ImportSpec defines a generated import statement.

func GatherAttributeImports

func GatherAttributeImports(genpkg string, att *expr.AttributeExpr) []*ImportSpec

GatherAttributeImports collects import specifications required by the given attribute, including meta-type imports and user types placed in external generated packages.

func GetMetaType

func GetMetaType(att *expr.AttributeExpr) (typeName string, importS *ImportSpec)

GetMetaType retrieves the type and package defined by the struct:field:type metadata if any.

func GetMetaTypeImports

func GetMetaTypeImports(att *expr.AttributeExpr) []*ImportSpec

GetMetaTypeImports parses the attribute for all user defined imports

func LoomImport added in v1.0.2

func LoomImport(rel string) *ImportSpec

LoomImport creates an import for a Loom package.

func LoomNamedImport added in v1.0.2

func LoomNamedImport(rel, name string) *ImportSpec

LoomNamedImport creates an import for a Loom package with the given name.

func NewImport

func NewImport(name, path string) *ImportSpec

NewImport creates an import spec.

func SimpleImport

func SimpleImport(path string) *ImportSpec

SimpleImport creates an import with no explicit path component.

func (*ImportSpec) Code

func (s *ImportSpec) Code() string

Code returns the Go import statement for the ImportSpec.

type InitArgData

type InitArgData struct {
	// Name is the argument name.
	Name string
	// Pointer if true indicates that the argument is a pointer.
	Pointer bool
	// Type is the argument type.
	Type expr.DataType
	// FieldName is the name of the field in the struct initialized by the
	// argument.
	FieldName string
	// FieldPointer if true indicates that the field in the struct is a
	// pointer.
	FieldPointer bool
	// FieldType is the type of the field in the struct.
	FieldType expr.DataType
}

InitArgData contains the data needed to render code to initialize struct fields with the given arguments.

type JenniferBuilder

type JenniferBuilder func(*jen.Statement)

JenniferBuilder renders one Go section using Jennifer.

type JenniferSection

type JenniferSection struct {
	// Name is the stable section identifier used by tests and merge logic.
	Name string
	// Build appends code to the provided statement.
	Build JenniferBuilder
}

JenniferSection renders a file section from a typed Jennifer statement.

func (*JenniferSection) SectionName

func (s *JenniferSection) SectionName() string

SectionName returns the stable section identifier.

func (*JenniferSection) Write

func (s *JenniferSection) Write(w io.Writer) error

Write writes the rendered Jennifer section to the given writer.

type Location

type Location struct {
	// FilePath is the path to the file.
	FilePath string
	// RelImportPath is the Go import path starting after the gen
	// folder.
	RelImportPath string
}

Location defines a file location and import details.

func UserTypeLocation

func UserTypeLocation(dt expr.DataType) *Location

UserTypeLocation returns the location of the user type if set via the struct:pkg:path metadata, nil otherwise..

func (*Location) PackageName

func (loc *Location) PackageName() string

PackageName returns the package name of the given location.

type MappedAttributeWalker

type MappedAttributeWalker func(name, elem string, required bool, a *expr.AttributeExpr) error

MappedAttributeWalker is the type of functions given to WalkMappedAttr. name is the name of the attribute, elem the name of the corresponding transport element (e.g. HTTP header). required is true if the attribute is required.

type NameScope

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

NameScope defines a naming scope.

func NewNameScope

func NewNameScope() *NameScope

NewNameScope creates an empty name scope.

func (*NameScope) GoFullTypeName

func (s *NameScope) GoFullTypeName(att *expr.AttributeExpr, pkg string) string

GoFullTypeName returns the Go type name of the given data type qualified with the given package name if applicable and if not the empty string.

func (*NameScope) GoFullTypeRef

func (s *NameScope) GoFullTypeRef(att *expr.AttributeExpr, pkg string) string

GoFullTypeRef returns the Go code that refers to the Go type which matches the given attribute type defined in the given package if a user type.

func (*NameScope) GoTypeDef

func (s *NameScope) GoTypeDef(att *expr.AttributeExpr, ptr, useDefault bool) string

GoTypeDef returns the Go code that defines a Go type which matches the data structure definition (the part that comes after `type foo`).

ptr if true indicates that the attribute must be stored in a pointer (except array and map types which are always non-pointers)

useDefault if true indicates that the attribute must not be a pointer if it has a default value.

func (*NameScope) GoTypeDefWithTargetPkg

func (s *NameScope) GoTypeDefWithTargetPkg(att *expr.AttributeExpr, ptr, useDefault bool, targetPkg string) string

GoTypeDefWithTargetPkg returns the Go type definition string, qualifying any user types inside inline structs with the provided target package. This helps when generating JSON-RPC client types that embed inline structs referencing user types defined in a separate package (e.g., gen/types).

func (*NameScope) GoTypeName

func (s *NameScope) GoTypeName(att *expr.AttributeExpr) string

GoTypeName returns the Go type name of the given attribute type.

func (*NameScope) GoTypeNameWithDefaults

func (s *NameScope) GoTypeNameWithDefaults(att *expr.AttributeExpr) string

GoTypeNameWithDefaults returns the Go type name of the given attribute type. The result of this function differs from GoTypeName when the attribute type is an object (note: not a user type) and the name is thus an inline struct definition. In this case accounting for default values may cause child attributes to use non-pointer fields.

func (*NameScope) GoTypeRef

func (s *NameScope) GoTypeRef(att *expr.AttributeExpr) string

GoTypeRef returns the Go code that refers to the Go type which matches the given attribute type.

func (*NameScope) GoTypeRefWithDefaults

func (s *NameScope) GoTypeRefWithDefaults(att *expr.AttributeExpr) string

GoTypeRefWithDefaults returns the Go code that refers to the Go type which matches the given attribute type. The result of this function differs from GoTypeRef when the attribute type is an object (note: not a user type) and the reference is thus an inline struct definition. In this case accounting for default values may cause child attributes to use non-pointer fields.

func (*NameScope) GoVar

func (*NameScope) GoVar(varName string, dt expr.DataType) string

GoVar returns the Go code that returns the address of a variable of the Go type which matches the given attribute type.

func (*NameScope) HashedUnique

func (s *NameScope) HashedUnique(key Hasher, name string, suffix ...string) string

HashedUnique builds the unique name for key using name and - if not unique - appending suffix and - if still not unique - a counter value. It returns the same value when called multiple times for a key returning the same hash.

func (*NameScope) Name

func (s *NameScope) Name(name string) string

Name returns a unique name for the given name by adding a counter value to the name until unique. It returns the same value when called multiple times for the same given name.

func (*NameScope) PeekUnique

func (s *NameScope) PeekUnique(name string, suffix ...string) string

PeekUnique returns the name that Unique would return for the same inputs, without mutating the scope.

This is useful when synthesizing type names or identifiers that are later reserved via Hash-based naming (e.g., GoTypeName/HashedUnique) and therefore must not increment the scope counters twice.

func (*NameScope) Unique

func (s *NameScope) Unique(name string, suffix ...string) string

Unique returns a unique name for the given name. A suffix is appended to the name if given name is not unique. If suffixed name is still not unique, a counter value is added to the suffixed name until unique.

type PrepareFunc

type PrepareFunc func(genpkg string, roots []eval.Root) error

PrepareFunc makes it possible to modify the design roots before the files being generated by the goa code generators or other plugins.

type RawSection

type RawSection struct {
	// Name is the stable section identifier used by tests and merge logic.
	Name string
	// Source is written as-is.
	Source string
}

RawSection renders an exact file section from a precomputed source string.

func (*RawSection) SectionName

func (s *RawSection) SectionName() string

SectionName returns the stable section identifier.

func (*RawSection) Write

func (s *RawSection) Write(w io.Writer) error

Write writes the raw section source to the given writer.

type Scoper

type Scoper interface {
	Scope() *NameScope
}

Scoper provides a scope for generating unique names.

type Section

type Section interface {
	// SectionName returns the stable section identifier used by tests and
	// merge logic.
	SectionName() string
	// Write writes the rendered section content to the given writer.
	Write(io.Writer) error
}

A Section renders one file fragment.

func MustJenniferSection

func MustJenniferSection(name string, build func(*jen.Statement)) Section

MustJenniferSection builds a Jennifer-backed section.

func NewJenniferSection

func NewJenniferSection(name string, build func(*jen.Statement)) Section

NewJenniferSection builds a Jennifer-backed section.

func NewRawSection

func NewRawSection(name, source string) Section

NewRawSection builds a raw source-backed section.

type SectionTemplate

type SectionTemplate struct {
	// Name is the name reported when parsing the source fails.
	Name string
	// Source is used to create the text/template.Template that
	// renders the section text.
	Source string
	// FuncMap lists the functions used to render the templates.
	FuncMap map[string]any
	// Data used as input of template.
	Data any
}

A SectionTemplate is a template and accompanying render data. The template format is described in the (stdlib) text/template package.

func Header(title, pack string, imports []*ImportSpec) *SectionTemplate

Header returns a Go source file header section template.

func (*SectionTemplate) SectionName

func (s *SectionTemplate) SectionName() string

SectionName returns the stable identifier of the section.

func (*SectionTemplate) Write

func (s *SectionTemplate) Write(w io.Writer) error

Write writes the section to the given writer.

type TransformAttrs

type TransformAttrs struct {
	// SourceCtx and TargetCtx are the source and target attribute context.
	SourceCtx, TargetCtx *AttributeContext
	// Prefix is the transform function helper prefix.
	Prefix string
}

TransformAttrs are the attributes that help in the transformation.

type TransformFunctionData

type TransformFunctionData struct {
	Name          string
	ParamTypeRef  string
	ResultTypeRef string
	Code          string
}

TransformFunctionData describes a helper function used to transform user types. These are necessary to prevent potential infinite recursion when a type attribute is defined recursively. For example:

var Recursive = Type("Recursive", func() {
    Attribute("r", "Recursive")
}

Transforming this type requires generating an intermediary function:

 func recursiveToRecursive(r *Recursive) *service.Recursive {
     var t service.Recursive
     if r.R != nil {
         t.R = recursiveToRecursive(r.R)
     }
}

func AppendHelpers

func AppendHelpers(oldH, newH []*TransformFunctionData) []*TransformFunctionData

AppendHelpers takes care of only appending helper functions from newH that are not already in oldH.

func GoTransform

func GoTransform(source, target *expr.AttributeExpr, sourceVar, targetVar string, sourceCtx, targetCtx *AttributeContext, prefix string, newVar bool) (string, []*TransformFunctionData, error)

GoTransform produces Go code that initializes the data structure defined by target from an instance of the data structure described by source. The data structures can be objects, arrays or maps. The algorithm matches object fields by name and ignores object fields in target that don't have a match in source. The matching and generated code leverage mapped attributes so that attribute names may use the "name:elem" syntax to define the name of the design attribute and the name of the corresponding generated Go struct field. The object field may also differ in that they may be pointers in one case and not the other. The function returns an error if target is not compatible with source (different type, fields of different type etc).

As a special case GoTransform can map union types from and to object types with two attributes, one called "Value" which stores the value and one called "Type" which is of type string and contains the value type name (union types are otherwise implemented as a struct containing a single field: the current value - however having the kind explicitly stored is required to serialize to JSON for example).

source and target are the attributes used in the transformation

sourceVar and targetVar are the variable names used in the transformation

sourceCtx and targetCtx are the attribute contexts for the source and target attributes

prefix is the transformation helper function prefix

newVar if true initializes a target variable with the generated Go code using `:=` operator. If false, it assigns Go code to the target variable using `=`.

func InitStructFields

func InitStructFields(args []*InitArgData, targetVar, sourcePkg, targetPkg string) (string, []*TransformFunctionData, error)

InitStructFields produces Go code to initialize a struct and its fields from the given init arguments.

Directories

Path Synopsis
Package cli contains helpers used by transport-specific command-line client generators for parsing the command-line flags to identify the service and the method to make a request along with the request payload to be sent.
Package cli contains helpers used by transport-specific command-line client generators for parsing the command-line flags to identify the service and the method to make a request along with the request payload to be sent.
Package codegentest provides utilities to assist writing unit test for codegen packages.
Package codegentest provides utilities to assist writing unit test for codegen packages.
Package example contains code generation algorithms to produce an example server and client implementation for the transports defined in the design.
Package example contains code generation algorithms to produce an example server and client implementation for the transports defined in the design.
Package generator contains the code generation algorithms for a service server, client, and OpenAPI specification.
Package generator contains the code generation algorithms for a service server, client, and OpenAPI specification.
Package service contains the code generation algorithms to produce code for the service and views packages and dummy implementation for the services defined in the design.
Package service contains the code generation algorithms to produce code for the service and views packages and dummy implementation for the services defined in the design.
Package template provides a shared template reader for codegen packages.
Package template provides a shared template reader for codegen packages.
Package testutil provides testing utilities for the Loom code generation framework.
Package testutil provides testing utilities for the Loom code generation framework.

Jump to

Keyboard shortcuts

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