template

package
v3.3.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2023 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ErrBadArgumentCount may be returned by a template invocation that has unpaired arguments
	ErrBadArgumentCount = fault.Const("bad argument count, must be in pairs")
	// ErrBadInvokeKeys may be returned by a template invocation that has invalid arguments keys
	ErrBadInvokeKeys = fault.Const("invoke keys must be strings")
)

Variables

View Source
var (
	// NodeTypeList exposes all the types valid as Is*name* tests
	NodeTypeList = []interface{}{

		"",
		false,

		semantic.BoolValue(true),
		semantic.StringValue(""),
		semantic.Int8Value(0),
		semantic.Uint8Value(0),
		semantic.Int16Value(0),
		semantic.Uint16Value(0),
		semantic.Int32Value(0),
		semantic.Uint32Value(0),
		semantic.Int64Value(0),
		semantic.Uint64Value(0),
		semantic.Float32Value(0),
		semantic.Float64Value(0),

		semantic.Abort{},
		semantic.Annotation{},
		semantic.API{},
		semantic.ArrayAssign{},
		semantic.ArrayIndex{},
		semantic.ArrayInitializer{},
		semantic.Assert{},
		semantic.Assign{},
		semantic.BinaryOp{},
		semantic.BitTest{},
		semantic.Block{},
		semantic.Branch{},
		semantic.Builtin{},
		semantic.Call{},
		semantic.Callable{},
		semantic.Cast{},
		semantic.Choice{},
		semantic.ClassInitializer{},
		semantic.Class{},
		semantic.Clone{},
		semantic.Copy{},
		semantic.Create{},
		semantic.DeclareLocal{},
		semantic.Definition{},
		semantic.DefinitionUsage{},
		semantic.EnumEntry{},
		semantic.Enum{},
		semantic.Fence{},
		semantic.Field{},
		semantic.FieldInitializer{},
		semantic.Function{},
		semantic.Global{},
		semantic.Ignore{},
		semantic.Iteration{},
		semantic.MapIteration{},
		semantic.Length{},
		semantic.Local{},
		semantic.Make{},
		semantic.MapAssign{},
		semantic.MapContains{},
		semantic.MapIndex{},
		semantic.MapRemove{},
		semantic.MapClear{},
		semantic.Map{},
		semantic.Member{},
		semantic.MessageValue{},
		semantic.New{},
		semantic.Null{},
		semantic.Observed{},
		semantic.Parameter{},
		semantic.PointerRange{},
		semantic.Pointer{},
		semantic.Print{},
		semantic.Pseudonym{},
		semantic.Read{},
		semantic.Reference{},
		semantic.Return{},
		semantic.Select{},
		semantic.SliceAssign{},
		semantic.SliceContains{},
		semantic.SliceIndex{},
		semantic.SliceRange{},
		semantic.Slice{},
		semantic.Slice{},
		semantic.StaticArray{},
		semantic.Switch{},
		semantic.UnaryOp{},
		semantic.Unknown{},
		semantic.Write{},

		(*semantic.Annotated)(nil),
		(*semantic.Expression)(nil),
		(*semantic.Type)(nil),
		(*semantic.Owned)(nil),
	}
)

Functions

This section is empty.

Types

type ConstantSets

type ConstantSets struct {
	Pack constset.Pack
	Sets map[semantic.Node]*int
}

ConstantSets consatins the constset.Pack, and each semantic mapping to a constset.Set index.

type Functions

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

func NewFunctions

func NewFunctions(ctx context.Context, api *semantic.API, mappings *semantic.Mappings, options Options) (*Functions, error)

NewFunctions builds a new template management object that can be used to run templates over an API file. The apiFile name is used in error messages, and should be the name of the file the api was loaded from. loader can be used to intercept file system access from within the templates, specifically used when including other templates. The functions in funcs are made available to the templates, and can override the functions from this package if needed.

func (*Functions) AllCommands

func (f *Functions) AllCommands(api interface{}) ([]*semantic.Function, error)

AllCommands returns a list of all cmd entries for a given API, regardless of whether they are free functions, class methods or pseudonym methods.

func (*Functions) AllCommandsSorted

func (f *Functions) AllCommandsSorted(api interface{}) ([]*semantic.Function, error)

AllCommandsSorted returns the list of commands retuned by AllCommands, sorted lexicographically.

func (*Functions) Args

func (f *Functions) Args(arguments ...interface{}) (interface{}, error)

Args builds a template argument object from a list of arguments. If no arguments are passed then the result will be nil. If a single argument is passed then the result will be the value of that argument. If the first argument is a map, it is assumed to be a base argument set to be augmented. Remaining arguments must come in name-value pairs. For example:

{{define "SingleParameterMacro"}}
    $ is: {{$}}
{{end}}

{{define "MultipleParameterMacro"}}
    $.ArgA is: {{$.ArgA}}, $.ArgB is: {{$.ArgB}}
{{end}}

{{template "SingleParameterMacro" (Args)}}
{{/* Returns "$ is: nil" */}}

{{template "SingleParameterMacro" (Args 42)}}
{{/* Returns "$ is: 42" */}}

{{template "MultipleParameterMacro" (Args "ArgA" 4 "ArgB" 2)}}
{{/* Returns "$.ArgA is: 4, $.ArgB is: 2" */}}

func (*Functions) AsSigned

func (*Functions) AsSigned(v interface{}) interface{}

AsSigned returns a signed reinterpretation of v of the same size if v an unsigned integer, or v if v a signed integer, otherwise nil.

func (*Functions) AssertType

func (*Functions) AssertType(v interface{}, expected ...string) (string, error)

Asserts that the type of v is in the list of expected types

func (*Functions) Bitpos

func (*Functions) Bitpos(v uint32) int

Bitpos returns the position of the only non-zero bit of v. If none or more than one bits are non-zero in v, returns -1.

func (Functions) CFieldName

func (Functions) CFieldName(obj interface{}) string

CFieldName converts an api name to a c field name.

func (Functions) CommandName

func (Functions) CommandName(obj interface{}) string

CommandName converts an api name to a command name.

func (*Functions) ConstantSetIndex

func (f *Functions) ConstantSetIndex(n semantic.Node) int

ConstantSetIndex returns the constant set for the given parameter.

func (*Functions) ConstantSets

func (f *Functions) ConstantSets() constset.Pack

ConstantSets returns the full constants set pack for the API.

func (Functions) Contains

func (Functions) Contains(substr string, v ...interface{}) bool

Contains returns true if any string segment contains substr.

func (*Functions) Decompose

func (f *Functions) Decompose(ty semantic.Type) semantic.Type

Decompose returns the fundamental building block of a type. The intent is to provide type information to enhance the memory display. Arrays and Slices are decomposed into their element type, other types decompose into their underlying type. The builtin string decomposes to char. Pointers decompose into pointers to their decomposed To type. AnyType is returned for composite types which do not decompose into a builtin, pointer or an enum. As a special case semantic.StringType is returned if ty is a pointer to "char*" or "const char*".

func (*Functions) Error

func (f *Functions) Error(s string, args ...interface{}) (string, error)

Error raises an error terminating execution of the template.

{{Error "Foo returned error: %s" $err}}

func (Functions) FilterOut

func (Functions) FilterOut(v, from stringList) stringList

FilterOut returns from with all occurances of v removed.

func (*Functions) ForEach

func (f *Functions) ForEach(arr interface{}, m string) (stringList, error)

ForEach returns a string list containing the strings emitted by calling the macro m for each sequential item in the array arr. 0 length strings will be ommitted from the returned list.

func (*Functions) Format

func (f *Functions) Format(command stringList, value string) (string, error)

Format reflows the string using an external command.

func (*Functions) GetAnnotation

func (*Functions) GetAnnotation(ty interface{}, name string) *semantic.Annotation

GetAnnotation finds and returns the annotation on ty with the specified name. If the annotation cannot be found, or ty does not support annotations then GetAnnotation returns nil.

func (*Functions) Global

func (f *Functions) Global(name string, values ...interface{}) (interface{}, error)

Gets or sets a template global variable Example:

{{Global "CatSays" "Meow"}}
The cat says: {{Global "CatSays"}}

func (Functions) GoCommandName

func (Functions) GoCommandName(obj interface{}) string

GoCommandName converts an api name to the public go command name form.

func (*Functions) GoFmt

func (f *Functions) GoFmt(value string) (string, error)

GoFmt reflows the string as if it were go code using the standard go fmt library.

func (Functions) GoPrivateName

func (Functions) GoPrivateName(obj interface{}) string

GoPrivateName converts an api name to the private go form.

func (Functions) GoPublicName

func (Functions) GoPublicName(obj interface{}) string

GoPublicName converts an api name to the public go form.

func (*Functions) HasMore

func (*Functions) HasMore(i int, l interface{}) bool

HasMore returns true if the i'th indexed item in l is not the last.

func (Functions) HasPrefix

func (Functions) HasPrefix(s string, prefix string) bool

HasPrefix tests whether the string s begins with prefix.

func (Functions) HasSuffix

func (Functions) HasSuffix(s string, suffix string) bool

HasSuffix tests whether the string s ends with suffix.

func (*Functions) Inc

func (f *Functions) Inc(name string) (interface{}, error)

Increments and returns a global variable Example:

{{Global "ProtoID" 0}}
bool field = {{Inc "ProtoID"}}

func (*Functions) Include

func (f *Functions) Include(templates ...string) error

Include loads each of the templates and executes their main bodies. The filenames are relative to the template doing the include.

func (*Functions) IndexOf

func (*Functions) IndexOf(array interface{}, value interface{}) int

IndexOf returns the index of value in the list array. If value is not found in array then IndexOf returns -1.

func (*Functions) IsNil

func (f *Functions) IsNil(v interface{}) bool

IsNil returns true if v is nil.

func (*Functions) IsNumericType

func (*Functions) IsNumericType(t interface{}) bool

IsNumericType returns true if t is one of the primitive numeric types.

func (*Functions) IsNumericValue

func (*Functions) IsNumericValue(v interface{}) bool

IsNumericValue returns true if v is one of the primitive numeric value types.

func (*Functions) IsStorageType

func (*Functions) IsStorageType(ty semantic.Type) bool

IsStorageType returns true if ty can be used as a storage type.

func (*Functions) Join

func (*Functions) Join(slices ...interface{}) []interface{}

Join returns the concatenation of all the passed array or slices into a single, sequential list.

func (Functions) JoinWith

func (Functions) JoinWith(sep string, v ...interface{}) string

JoinWith returns the concatenation of all the string segments with the specified separator.

func (*Functions) Length

func (f *Functions) Length(arr interface{}) (int, error)

func (*Functions) Log

func (f *Functions) Log(s string, args ...interface{}) string

Log prints s and optional format arguments to stdout. Example:

{{Log "%s %s" "Hello" "world}}

func (Functions) Lower

func (Functions) Lower(v ...interface{}) stringList

Lower lower-cases all letters of each string segment.

func (*Functions) Macro

func (f *Functions) Macro(name string, arguments ...interface{}) (string, error)

Macro invokes the template macro with the specified name and returns the template output as a string. See Args for how the arguments are processed.

func (Functions) NameOf

func (Functions) NameOf(obj interface{}) string

NameOf returns the name of the supplied object if it has one.

func (*Functions) NewReflow

func (f *Functions) NewReflow(indent string, value string) (string, error)

NewReflow reformats the value using the reflow package.

func (*Functions) Node

func (f *Functions) Node(prefix string, node semantic.Node, arguments ...interface{}) (string, error)

Node dispatches to the template that matches the node best, writing the result to the current output writer. If the node is a Type or Expression then the type semantic.Type name is tried, then the class of type (the name of the semantic class that represents the type). The actual name of the node type is then tried, and if none of those matches, the "Default" template is used if present. If no possible template could be matched, and error is generated. eg: {{Node "TypeName" $}} where $ is a boolean and expression would try

"TypeName#Bool"
"TypeName.Builtin"
"TypeName.BinaryOp"
"TypeName_Default"

See Args for how the arguments are processed, in addition the Node arg will be added in and have the value of node, and if the node had a type discovered, the Type arg will be added in as well.

func (*Functions) Partition

func (f *Functions) Partition(arr interface{}, keyMacro string, num int) (interface{}, error)

Divides a slice into num buckets and returns a slice of new slices. keyMacro is the name of a macro which should generate a stable key for the object in the slice.

func (*Functions) PartitionByKey

func (f *Functions) PartitionByKey(arr interface{}, keyMacro string) (interface{}, error)

PartitionByKey Divides a slice into one bucket for each different keyMacro returned. keyMacro is the name of a macro which should generate a stable key for the object in the slice.

func (Functions) ProtoCppName

func (Functions) ProtoCppName(obj interface{}) string

ProtoCppName converts an api name to the cpp name produced by the proto compiler.

func (Functions) ProtoGoName

func (Functions) ProtoGoName(obj interface{}) string

ProtoGoName converts an api name to the go name produced by the proto compiler.

func (Functions) ProtoName

func (Functions) ProtoName(obj interface{}) string

ProtoName converts an api name to the proto name.

func (*Functions) ProtoType

func (f *Functions) ProtoType(ty interface{}) string

ProtoType returns the proto type name for the given type.

func (*Functions) Reflow

func (f *Functions) Reflow(indentSize int, value string) (string, error)

Reflow does the primitive reflow, but no language specific handling.

func (Functions) Replace

func (Functions) Replace(old string, new string, v ...interface{}) stringList

Replace any occurance of old with new in the string segments.

func (*Functions) Reverse

func (*Functions) Reverse(in interface{}) interface{}

Reverse returns a new list with all the elements of in reversed.

func (*Functions) SNode

func (f *Functions) SNode(prefix string, node semantic.Node, arguments ...interface{}) (string, error)

SNode dispatches to the template that matches the node best, capturing the result and returning it. See Node for the dispatch rules used.

func (*Functions) SortBy

func (f *Functions) SortBy(arr interface{}, keyMacro string) (interface{}, error)

SortBy returns a new list containing the sorted elements of arr. The list is sorted by the string values returned by calling the template function keyMacro with each element in the list.

func (Functions) SplitEOL

func (f Functions) SplitEOL(v ...interface{}) stringList

SplitEOL slices each string segement into all substrings separated by an end of line delimiter (\n or \r\n). The returned stringList will not contain any new lines.

func (Functions) SplitOn

func (Functions) SplitOn(sep string, v ...interface{}) stringList

SplitOn slices each string segement into all substrings separated by sep. The returned stringList will not contain any occurances of sep.

func (Functions) SplitPascalCase

func (Functions) SplitPascalCase(v ...interface{}) stringList

SplitPascalCase slices each string segment at each transition from an letter rune to a upper-case letter rune.

func (Functions) SplitUpperCase

func (Functions) SplitUpperCase(v ...interface{}) stringList

SplitUpperCase slices each string segment before and after each upper-case rune.

func (Functions) Strings

func (Functions) Strings(v ...interface{}) stringList

Strings returns the arguments as a string list.

func (*Functions) Tail

func (*Functions) Tail(start int, array interface{}) interface{}

Tail returns a slice of the list from start to len(array).

func (*Functions) TargetField

func (f *Functions) TargetField(e semantic.Expression) interface{}

TargetField returns the *semantic.Field if e is an expression that refers to a class field, otherwise nil.

func (*Functions) Template

func (f *Functions) Template(name string, arguments ...interface{}) (string, error)

Template invokes the template with the specified name writing the output to the current output writer. See Args for how the arguments are processed.

func (Functions) Title

func (Functions) Title(v ...interface{}) stringList

Title capitalizes each letter of each string segment.

func (*Functions) TokenOf

func (f *Functions) TokenOf(v semantic.Node) string

TokenOf returns the cst token string that represents the supplied semantic node

func (Functions) TrimLeft

func (Functions) TrimLeft(cutset string, from ...interface{}) stringList

TrimLeft returns from with the all leading Unicode code points contained in cutset removed.

func (Functions) TrimPrefix

func (Functions) TrimPrefix(prefix string, from ...interface{}) stringList

TrimPrefix returns from with without the provided leading prefix string.

func (Functions) TrimRight

func (Functions) TrimRight(cutset string, from ...interface{}) stringList

TrimRight returns from with the all trailing Unicode code points contained in cutset removed.

func (Functions) TrimSuffix

func (Functions) TrimSuffix(suffix string, from ...interface{}) stringList

TrimSuffix returns from without the provided trailing suffix string.

func (*Functions) TypeOf

func (*Functions) TypeOf(v semantic.Node) (semantic.Type, error)

TypeOf returns the resolved semantic type of an expression node.

func (*Functions) Underlying

func (f *Functions) Underlying(ty semantic.Type) semantic.Type

Underlying returns the underlying type for ty by recursively traversing the pseudonym chain until reaching and returning the first non-pseudoym type. If ty is not a pseudonym then it is simply returned.

func (*Functions) UniqueEnumKeys

func (*Functions) UniqueEnumKeys(e *semantic.Enum) ([]*semantic.EnumEntry, error)

UniqueEnumKeys returns the enum's list of EnumEntry with duplicate values removed. To remove duplicates the entry with the shortest name is picked.

func (*Functions) Unpack

func (*Functions) Unpack(v interface{}) interface{}

Unpack throws away type information to work around template system limitations When you have a value of an interface type that carries methods, it fails to introspect the concrete type for its members, so the template can't see them. The result of Upack no longer has a type, so the concrete type members become visible.

func (Functions) Untitle

func (Functions) Untitle(v ...interface{}) stringList

Untitle lower-cases each letter of each string segment.

func (Functions) Upper

func (Functions) Upper(v ...interface{}) stringList

Upper upper-cases all letters of each string segment.

func (*Functions) WithAnnotation

func (*Functions) WithAnnotation(name string, l interface{}) []interface{}

WithAnnotation returns the list l filtered to those items with the specified annotation.

func (*Functions) WithoutAnnotation

func (*Functions) WithoutAnnotation(name string, l interface{}) []interface{}

WithoutAnnotation returns the list l filtered to those items without the specified annotation.

func (*Functions) Write

func (f *Functions) Write(fileName string, value string) (string, error)

Write takes a string and writes it into the specified file. The filename is relative to the output directory.

type Options

type Options struct {
	Dir     string
	APIFile string
	Loader  func(filename string) ([]byte, error)
	Funcs   template.FuncMap
	Globals []string
	Tracer  string
}

Jump to

Keyboard shortcuts

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