hcl
packageThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Index¶
- Variables
- func AbsTraversalForExpr(expr Expression) (Traversal, Diagnostics)
- func ExprAsKeyword(expr Expression) string
- func ExprCall(expr Expression) (*StaticCall, Diagnostics)
- func ExprList(expr Expression) ([]Expression, Diagnostics)
- func ExprMap(expr Expression) ([]KeyValuePair, Diagnostics)
- func RelTraversalForExpr(expr Expression) (Traversal, Diagnostics)
- type Attribute
- type AttributeSchema
- type Attributes
- type Block
- type BlockHeaderSchema
- type Blocks
- type Body
- type BodyContent
- type BodySchema
- type Diagnostic
- type DiagnosticSeverity
- type DiagnosticWriter
- type Diagnostics
- type EvalContext
- type Expression
- type File
- type KeyValuePair
- type Pos
- type Range
- func (r Range) CanSliceBytes(b []byte) bool
- func (r Range) ContainsOffset(offset int) bool
- func (r Range) ContainsPos(pos Pos) bool
- func (r Range) Empty() bool
- func (r Range) Overlap(other Range) Range
- func (r Range) Overlaps(other Range) bool
- func (r Range) PartitionAround(other Range) (before, overlap, after Range)
- func (r Range) Ptr() *Range
- func (r Range) SliceBytes(b []byte) []byte
- func (r Range) String() string
- type RangeScanner
- type StaticCall
- type Traversal
- func (t Traversal) IsRelative() bool
- func (t Traversal) RootName() string
- func (t Traversal) SimpleSplit() TraversalSplit
- func (t Traversal) SourceRange() Range
- func (t Traversal) TraverseAbs(ctx *EvalContext) (cty.Value, Diagnostics)
- func (t Traversal) TraverseRel(val cty.Value) (cty.Value, Diagnostics)
- type TraversalSplit
- func (t TraversalSplit) Join() Traversal
- func (t TraversalSplit) RootName() string
- func (t TraversalSplit) Traverse(ctx *EvalContext) (cty.Value, Diagnostics)
- func (t TraversalSplit) TraverseAbs(ctx *EvalContext) (cty.Value, Diagnostics)
- func (t TraversalSplit) TraverseRel(val cty.Value) (cty.Value, Diagnostics)
- type TraverseAttr
- type TraverseIndex
- type TraverseRoot
- type TraverseSplat
- type Traverser
Constants¶
This section is empty.
Variables¶
var InitialPos =Pos{Byte: 0, Line: 1, Column: 1}InitialPos is a suitable position to use to mark the start of a file.
Functions¶
funcAbsTraversalForExpr¶
func AbsTraversalForExpr(exprExpression) (Traversal,Diagnostics)
AbsTraversalForExpr attempts to interpret the given expression asan absolute traversal, or returns error diagnostic(s) if that isnot possible for the given expression.
A particular Expression implementation can support this function byoffering a method called AsTraversal that takes no arguments andreturns either a valid absolute traversal or nil to indicate thatno traversal is possible. Alternatively, an implementation can supportUnwrapExpression to delegate handling of this function to a wrappedExpression object.
In most cases the calling application is interested in the valuethat results from an expression, but in rarer cases the applicationneeds to see the the name of the variable and subsequentattributes/indexes itself, for example to allow users to give referencesto the variables themselves rather than to their values. An implementerof this function should at least support attribute and index steps.
funcExprAsKeyword¶
func ExprAsKeyword(exprExpression)string
ExprAsKeyword attempts to interpret the given expression as a static keyword,returning the keyword string if possible, and the empty string if not.
A static keyword, for the sake of this function, is a single identifier.For example, the following attribute has an expression that would producethe keyword "foo":
example = foo
This function is a variant of AbsTraversalForExpr, which uses the sameinterface on the given expression. This helper constrains the resultfurther by requiring only a single root identifier.
This function is intended to be used with the following idiom, to recognizesituations where one of a fixed set of keywords is required and arbitraryexpressions are not allowed:
switch hcl.ExprAsKeyword(expr) {case "allow": // (take suitable action for keyword "allow")case "deny": // (take suitable action for keyword "deny")default: diags = append(diags, &hcl.Diagnostic{ // ... "invalid keyword" diagnostic message ... })}The above approach will generate the same message for both the use of anunrecognized keyword and for not using a keyword at all, which is usuallyreasonable if the message specifies that the given value must be a keywordfrom that fixed list.
Note that in the native syntax the keywords "true", "false", and "null" arerecognized as literal values during parsing and so these reserved wordscannot not be accepted as keywords by this function.
Since interpreting an expression as a keyword bypasses usual expressionevaluation, it should be used sparingly for situations where e.g. one ofa fixed set of keywords is used in a structural way in a special attributeto affect the further processing of a block.
funcExprCall¶
func ExprCall(exprExpression) (*StaticCall,Diagnostics)
ExprCall tests if the given expression is a function call and,if so, extracts the function name and the expressions that representthe arguments. If the given expression is not statically a function call,error diagnostics are returned.
A particular Expression implementation can support this function byoffering a method called ExprCall that takes no arguments and returns*StaticCall. This method should return nil if a static call cannotbe extracted. Alternatively, an implementation can supportUnwrapExpression to delegate handling of this function to a wrappedExpression object.
funcExprList¶
func ExprList(exprExpression) ([]Expression,Diagnostics)
ExprList tests if the given expression is a static list construct and,if so, extracts the expressions that represent the list elements.If the given expression is not a static list, error diagnostics arereturned.
A particular Expression implementation can support this function byoffering a method called ExprList that takes no arguments and returns[]Expression. This method should return nil if a static list cannotbe extracted. Alternatively, an implementation can supportUnwrapExpression to delegate handling of this function to a wrappedExpression object.
funcExprMap¶
func ExprMap(exprExpression) ([]KeyValuePair,Diagnostics)
ExprMap tests if the given expression is a static map construct and,if so, extracts the expressions that represent the map elements.If the given expression is not a static map, error diagnostics arereturned.
A particular Expression implementation can support this function byoffering a method called ExprMap that takes no arguments and returns[]KeyValuePair. This method should return nil if a static map cannotbe extracted. Alternatively, an implementation can supportUnwrapExpression to delegate handling of this function to a wrappedExpression object.
funcRelTraversalForExpr¶
func RelTraversalForExpr(exprExpression) (Traversal,Diagnostics)
RelTraversalForExpr is similar to AbsTraversalForExpr but it returnsa relative traversal instead. Due to the nature of HCL expressions, thefirst element of the returned traversal is always a TraverseAttr, andthen it will be followed by zero or more other expressions.
Any expression accepted by AbsTraversalForExpr is also accepted byRelTraversalForExpr.
Types¶
typeAttribute¶
type Attribute struct {NamestringExprExpressionRangeRangeNameRangeRange}Attribute represents an attribute from within a body.
typeAttributeSchema¶
AttributeSchema represents the requirements for an attribute, and is usedfor matching attributes within bodies.
typeAttributes¶
Attributes is a set of attributes keyed by their names.
typeBlock¶
type Block struct {TypestringLabels []stringBodyBodyDefRangeRange// Range that can be considered the "definition" for seeking in an editorTypeRangeRange// Range for the block type declaration specifically.LabelRanges []Range// Ranges for the label values specifically.}Block represents a nested block within a Body.
typeBlockHeaderSchema¶
BlockHeaderSchema represents the shape of a block header, and isused for matching blocks within bodies.
typeBlocks¶
type Blocks []*Block
Blocks is a sequence of Block.
typeBody¶
type Body interface {// Content verifies that the entire body content conforms to the given// schema and then returns it, and/or returns diagnostics. The returned// body content is valid if non-nil, regardless of whether Diagnostics// are provided, but diagnostics should still be eventually shown to// the user.Content(schema *BodySchema) (*BodyContent,Diagnostics)// PartialContent is like Content except that it permits the configuration// to contain additional blocks or attributes not specified in the// schema. If any are present, the returned Body is non-nil and contains// the remaining items from the body that were not selected by the schema.PartialContent(schema *BodySchema) (*BodyContent,Body,Diagnostics)// JustAttributes attempts to interpret all of the contents of the body// as attributes, allowing for the contents to be accessed without a priori// knowledge of the structure.//// The behavior of this method depends on the body's source language.// Some languages, like JSON, can't distinguish between attributes and// blocks without schema hints, but for languages that _can_ error// diagnostics will be generated if any blocks are present in the body.//// Diagnostics may be produced for other reasons too, such as duplicate// declarations of the same attribute.JustAttributes() (Attributes,Diagnostics)// MissingItemRange returns a range that represents where a missing item// might hypothetically be inserted. This is used when producing// diagnostics about missing required attributes or blocks. Not all bodies// will have an obvious single insertion point, so the result here may// be rather arbitrary.MissingItemRange()Range}Body is a container for attributes and blocks. It serves as the primaryunit of hierarchical structure within configuration.
The content of a body cannot be meaningfully interpreted without a schema,so Body represents the raw body content and has methods that allow thecontent to be extracted in terms of a given schema.
funcEmptyBody¶
func EmptyBody()Body
EmptyBody returns a body with no content. This body can be used as aplaceholder when a body is required but no body content is available.
funcMergeBodies¶
MergeBodies is like MergeFiles except it deals directly with bodies, ratherthan with entire files.
funcMergeFiles¶
MergeFiles combines the given files to produce a single body that containsconfiguration from all of the given files.
The ordering of the given files decides the order in which containedelements will be returned. If any top-level attributes are defined withthe same name across multiple files, a diagnostic will be produced fromthe Content and PartialContent methods describing this error in auser-friendly way.
typeBodyContent¶
type BodyContent struct {AttributesAttributesBlocksBlocksMissingItemRangeRange}BodyContent is the result of applying a BodySchema to a Body.
typeBodySchema¶
type BodySchema struct {Attributes []AttributeSchemaBlocks []BlockHeaderSchema}BodySchema represents the desired shallow structure of a body.
typeDiagnostic¶
type Diagnostic struct {SeverityDiagnosticSeverity// Summary and Detail contain the English-language description of the// problem. Summary is a terse description of the general problem and// detail is a more elaborate, often-multi-sentence description of// the probem and what might be done to solve it.SummarystringDetailstring// Subject and Context are both source ranges relating to the diagnostic.//// Subject is a tight range referring to exactly the construct that// is problematic, while Context is an optional broader range (which should// fully contain Subject) that ought to be shown around Subject when// generating isolated source-code snippets in diagnostic messages.// If Context is nil, the Subject is also the Context.//// Some diagnostics have no source ranges at all. If Context is set then// Subject should always also be set.Subject *RangeContext *Range// For diagnostics that occur when evaluating an expression, Expression// may refer to that expression and EvalContext may point to the// EvalContext that was active when evaluating it. This may allow for the// inclusion of additional useful information when rendering a diagnostic// message to the user.//// It is not always possible to select a single EvalContext for a// diagnostic, and so in some cases this field may be nil even when an// expression causes a problem.//// EvalContexts form a tree, so the given EvalContext may refer to a parent// which in turn refers to another parent, etc. For a full picture of all// of the active variables and functions the caller must walk up this// chain, preferring definitions that are "closer" to the expression in// case of colliding names.ExpressionExpressionEvalContext *EvalContext}Diagnostic represents information to be presented to a user about anerror or anomoly in parsing or evaluating configuration.
func (*Diagnostic)Error¶
func (d *Diagnostic) Error()string
error implementation, so that diagnostics can be returned via APIsthat normally deal in vanilla Go errors.
This presents only minimal context about the error, for compatibilitywith usual expectations about how errors will present as strings.
typeDiagnosticSeverity¶
type DiagnosticSeverityint
DiagnosticSeverity represents the severity of a diagnostic.
const (// DiagInvalid is the invalid zero value of DiagnosticSeverityDiagInvalidDiagnosticSeverity =iota// DiagError indicates that the problem reported by a diagnostic prevents// further progress in parsing and/or evaluating the subject.DiagError// DiagWarning indicates that the problem reported by a diagnostic warrants// user attention but does not prevent further progress. It is most// commonly used for showing deprecation notices.DiagWarning)
typeDiagnosticWriter¶
type DiagnosticWriter interface {WriteDiagnostic(*Diagnostic)errorWriteDiagnostics(Diagnostics)error}A DiagnosticWriter emits diagnostics somehow.
funcNewDiagnosticTextWriter¶
func NewDiagnosticTextWriter(wrio.Writer, files map[string]*File, widthuint, colorbool)DiagnosticWriter
NewDiagnosticTextWriter creates a DiagnosticWriter that writes diagnosticsto the given writer as formatted text.
It is designed to produce text appropriate to print in a monospaced fontin a terminal of a particular width, or optionally with no width limit.
The given width may be zero to disable word-wrapping of the detail textand truncation of source code snippets.
If color is set to true, the output will include VT100 escape sequences tocolor-code the severity indicators. It is suggested to turn this off ifthe target writer is not a terminal.
typeDiagnostics¶
type Diagnostics []*Diagnostic
Diagnostics is a list of Diagnostic instances.
funcApplyPath¶
ApplyPath is a helper function that applies a cty.Path to a value using theindexing and attribute access operations from HCL.
This is similar to calling the path's own Apply method, but ApplyPath usesthe more relaxed typing rules that apply to these operations in HCL, ratherthan cty's relatively-strict rules. ApplyPath is implemented in terms ofIndex and GetAttr, and so it has the same behavior for individual stepsbut will stop and return any errors returned by intermediate steps.
Diagnostics are produced if the given path cannot be applied to the givenvalue. Therefore a pointer to a source range must be provided to use indiagnostics, though nil can be provided if the calling application is goingto ignore the subject of the returned diagnostics anyway.
funcGetAttr¶
GetAttr is a helper function that performs the same operation as theattribute access in the HCL expression language. That is, the result is thesame as it would be for obj.attr in a configuration expression.
This is exported so that applications can access attributes in a mannerconsistent with how the language does it, including handling of null andunknown values, etc.
Diagnostics are produced if the given combination of values is not valid.Therefore a pointer to a source range must be provided to use in diagnostics,though nil can be provided if the calling application is going toignore the subject of the returned diagnostics anyway.
funcIndex¶
Index is a helper function that performs the same operation as the indexoperator in the HCL expression language. That is, the result is thesame as it would be for collection[key] in a configuration expression.
This is exported so that applications can perform indexing in a mannerconsistent with how the language does it, including handling of null andunknown values, etc.
Diagnostics are produced if the given combination of values is not valid.Therefore a pointer to a source range must be provided to use in diagnostics,though nil can be provided if the calling application is going toignore the subject of the returned diagnostics anyway.
func (Diagnostics)Append¶
func (dDiagnostics) Append(diag *Diagnostic)Diagnostics
Append appends a new error to a Diagnostics and return the whole Diagnostics.
This is provided as a convenience for returning from a function thatcollects and then returns a set of diagnostics:
return nil, diags.Append(&hcl.Diagnostic{ ... })Note that this modifies the array underlying the diagnostics slice, somust be used carefully within a single codepath. It is incorrect (and rude)to extend a diagnostics created by a different subsystem.
func (Diagnostics)Error¶
func (dDiagnostics) Error()string
error implementation, so that sets of diagnostics can be returned viaAPIs that normally deal in vanilla Go errors.
func (Diagnostics)Errs¶
func (dDiagnostics) Errs() []error
func (Diagnostics)Extend¶
func (dDiagnostics) Extend(diagsDiagnostics)Diagnostics
Extend concatenates the given Diagnostics with the receiver and returnsthe whole new Diagnostics.
This is similar to Append but accepts multiple diagnostics to add. It hasall the same caveats and constraints.
func (Diagnostics)HasErrors¶
func (dDiagnostics) HasErrors()bool
HasErrors returns true if the receiver contains any diagnostics ofseverity DiagError.
typeEvalContext¶
type EvalContext struct {Variables map[string]cty.ValueFunctions map[string]function.Function// contains filtered or unexported fields}An EvalContext provides the variables and functions that should be usedto evaluate an expression.
func (*EvalContext)NewChild¶
func (ctx *EvalContext) NewChild() *EvalContext
NewChild returns a new EvalContext that is a child of the receiver.
func (*EvalContext)Parent¶
func (ctx *EvalContext) Parent() *EvalContext
Parent returns the parent of the receiver, or nil if the receiver hasno parent.
typeExpression¶
type Expression interface {// Value returns the value resulting from evaluating the expression// in the given evaluation context.//// The context may be nil, in which case the expression may contain// only constants and diagnostics will be produced for any non-constant// sub-expressions. (The exact definition of this depends on the source// language.)//// The context may instead be set but have either its Variables or// Functions maps set to nil, in which case only use of these features// will return diagnostics.//// Different diagnostics are provided depending on whether the given// context maps are nil or empty. In the former case, the message// tells the user that variables/functions are not permitted at all,// while in the latter case usage will produce a "not found" error for// the specific symbol in question.Value(ctx *EvalContext) (cty.Value,Diagnostics)// Variables returns a list of variables referenced in the receiving// expression. These are expressed as absolute Traversals, so may include// additional information about how the variable is used, such as// attribute lookups, which the calling application can potentially use// to only selectively populate the scope.Variables() []TraversalRange()RangeStartRange()Range}Expression is a literal value or an expression provided in theconfiguration, which can be evaluated within a scope to produce a value.
funcStaticExpr¶
func StaticExpr(valcty.Value, rngRange)Expression
StaticExpr returns an Expression that always evaluates to the given value.
This is useful to substitute default values for expressions that arenot explicitly given in configuration and thus would otherwise have noExpression to return.
Since expressions are expected to have a source range, the caller mustprovide one. Ideally this should be a real source range, but it canbe a synthetic one (with an empty-string filename) if no suitable rangeis available.
funcUnwrapExpression¶
func UnwrapExpression(exprExpression)Expression
UnwrapExpression removes any "wrapper" expressions from the given expression,to recover the representation of the physical expression given in sourcecode.
Sometimes wrapping expressions are used to modify expression behavior, e.g.in extensions that need to make some local variables available to certainsub-trees of the configuration. This can make it difficult to reliablytype-assert on the physical AST types used by the underlying syntax.
Unwrapping an expression may modify its behavior by stripping away anyadditional constraints or capabilities being applied to the Value andVariables methods, so this function should generally only be used priorto operations that concern themselves with the static syntax of the inputconfiguration, and not with the effective value of the expression.
Wrapper expression types must support unwrapping by implementing a methodcalled UnwrapExpression that takes no arguments and returns the embeddedExpression. Implementations of this method should peel away only one levelof wrapping, if multiple are present. This method may return nil toindicate _dynamically_ that no wrapped expression is available, forexpression types that might only behave as wrappers in certain cases.
funcUnwrapExpressionUntil¶
func UnwrapExpressionUntil(exprExpression, until func(Expression)bool)Expression
UnwrapExpressionUntil is similar to UnwrapExpression except it gives thecaller an opportunity to test each level of unwrapping to see each aparticular expression is accepted.
This could be used, for example, to unwrap until a particular otherinterface is satisfied, regardless of wrap wrapping level it is satisfiedat.
The given callback function must return false to continue wrapping, ortrue to accept and return the proposed expression given. If the callbackfunction rejects even the final, physical expression then the result ofthis function is nil.
typeFile¶
type File struct {BodyBodyBytes []byte// Nav is used to integrate with the "hcled" editor integration package,// and with diagnostic information formatters. It is not for direct use// by a calling application.Nav interface{}}File is the top-level node that results from parsing a HCL file.
func (*File)AttributeAtPos¶
AttributeAtPos attempts to find an attribute definition in the receivingfile that contains the given position. This is a best-effort method that maynot be able to produce a result for all positions or for all HCL syntaxes.
The result is nil if no single attribute could be selected for any reason.
func (*File)BlocksAtPos¶
BlocksAtPos attempts to find all of the blocks that contain the givenposition, ordered so that the outermost block is first and the innermostblock is last. This is a best-effort method that may not be able to producea complete result for all positions or for all HCL syntaxes.
If the returned slice is non-empty, the first element is guaranteed torepresent the same block as would be the result of OutermostBlockAtPos andthe last element the result of InnermostBlockAtPos. However, theimplementation may return two different objects describing the same block,so comparison by pointer identity is not possible.
The result is nil if no blocks at all contain the given position.
func (*File)InnermostBlockAtPos¶
InnermostBlockAtPos attempts to find the most deeply-nested block in thereceiving file that contains the given position. This is a best-effortmethod that may not be able to produce a result for all positions or forall HCL syntaxes.
The result is nil if no single block could be selected for any reason.
func (*File)OutermostBlockAtPos¶
OutermostBlockAtPos attempts to find a top-level block in the receiving filethat contains the given position. This is a best-effort method that may notbe able to produce a result for all positions or for all HCL syntaxes.
The result is nil if no single block could be selected for any reason.
func (*File)OutermostExprAtPos¶
func (f *File) OutermostExprAtPos(posPos)Expression
OutermostExprAtPos attempts to find an expression in the receiving filethat contains the given position. This is a best-effort method that may notbe able to produce a result for all positions or for all HCL syntaxes.
Since expressions are often nested inside one another, this method returnsthe outermost "root" expression that is not contained by any other.
The result is nil if no single expression could be selected for any reason.
typeKeyValuePair¶
type KeyValuePair struct {KeyExpressionValueExpression}KeyValuePair represents a pair of expressions that serve as a single itemwithin a map or object definition construct.
typePos¶
type Pos struct {// Line is the source code line where this position points. Lines are// counted starting at 1 and incremented for each newline character// encountered.Lineint// Column is the source code column where this position points, in// unicode characters, with counting starting at 1.//// Column counts characters as they appear visually, so for example a// latin letter with a combining diacritic mark counts as one character.// This is intended for rendering visual markers against source code in// contexts where these diacritics would be rendered in a single character// cell. Technically speaking, Column is counting grapheme clusters as// used in unicode normalization.Columnint// Byte is the byte offset into the file where the indicated character// begins. This is a zero-based offset to the first byte of the first// UTF-8 codepoint sequence in the character, and thus gives a position// that can be resolved _without_ awareness of Unicode characters.Byteint}Pos represents a single position in a source file, by addressing thestart byte of a unicode character encoded in UTF-8.
Pos is generally used only in the context of a Range, which then defineswhich source file the position is within.
typeRange¶
type Range struct {// Filename is the name of the file into which this range's positions// point.Filenamestring// Start and End represent the bounds of this range. Start is inclusive// and End is exclusive.Start, EndPos}Range represents a span of characters between two positions in a sourcefile.
This struct is usually used by value in types that represent AST nodes,but by pointer in types that refer to the positions of other objects,such as in diagnostics.
funcRangeBetween¶
RangeBetween returns a new range that spans from the beginning of thestart range to the end of the end range.
The result is meaningless if the two ranges do not belong to the samesource file or if the end range appears before the start range.
funcRangeOver¶
RangeOver returns a new range that covers both of the given ranges andpossibly additional content between them if the two ranges do not overlap.
If either range is empty then it is ignored. The result is empty if bothgiven ranges are empty.
The result is meaningless if the two ranges to not belong to the samesource file.
func (Range)CanSliceBytes¶
CanSliceBytes returns true if SliceBytes could return an accuratesub-slice of the given slice.
This effectively tests whether the start and end offsets of the rangeare within the bounds of the slice, and thus whether SliceBytes can betrusted to produce an accurate start and end position within that slice.
func (Range)ContainsOffset¶
ContainsOffset returns true if and only if the given byte offset is withinthe receiving Range.
func (Range)ContainsPos¶
ContainsPos returns true if and only if the given position is contained withinthe receiving range.
In the unlikely case that the line/column information disagree with the byteoffset information in the given position or receiving range, the byteoffsets are given priority.
func (Range)Overlap¶
Overlap finds a range that is either identical to or a sub-range of boththe receiver and the other given range. It returns an empty rangewithin the receiver if there is no overlap between the two ranges.
A non-empty result is either identical to or a subset of the receiver.
func (Range)Overlaps¶
Overlaps returns true if the receiver and the other given range share anycharacters in common.
func (Range)PartitionAround¶
PartitionAround finds the portion of the given range that overlaps withthe reciever and returns three ranges: the portion of the reciever thatprecedes the overlap, the overlap itself, and then the portion of thereciever that comes after the overlap.
If the two ranges do not overlap then all three returned ranges are empty.
If the given range aligns with or extends beyond either extent of thereciever then the corresponding outer range will be empty.
func (Range)Ptr¶
Ptr returns a pointer to a copy of the receiver. This is a convenience whenranges in places where pointers are required, such as in Diagnostic, butthe range in question is returned from a method. Go would otherwise notallow one to take the address of a function call.
func (Range)SliceBytes¶
SliceBytes returns a sub-slice of the given slice that is covered by thereceiving range, assuming that the given slice is the source code of thefile indicated by r.Filename.
If the receiver refers to any byte offsets that are outside of the slicethen the result is constrained to the overlapping portion only, to avoida panic. Use CanSliceBytes to determine if the result is guaranteed tobe an accurate span of the requested range.
typeRangeScanner¶
type RangeScanner struct {// contains filtered or unexported fields}RangeScanner is a helper that will scan over a buffer using a bufio.SplitFuncand visit a source range for each token matched.
For example, this can be used with bufio.ScanLines to find the source rangefor each line in the file, skipping over the actual newline characters, whichmay be useful when printing source code snippets as part of diagnosticmessages.
The line and column information in the returned ranges is produced bycounting newline characters and grapheme clusters respectively, whichmimics the behavior we expect from a parser when producing ranges.
funcNewRangeScanner¶
func NewRangeScanner(b []byte, filenamestring, cbbufio.SplitFunc) *RangeScanner
NewRangeScanner creates a new RangeScanner for the given buffer, producingranges for the given filename.
Since ranges have grapheme-cluster granularity rather than byte granularity,the scanner will produce incorrect results if the given SplitFunc createstokens between grapheme cluster boundaries. In particular, it is incorrectto use RangeScanner with bufio.ScanRunes because it will produce tokensaround individual UTF-8 sequences, which will split any multi-sequencegrapheme clusters.
funcNewRangeScannerFragment¶
NewRangeScannerFragment is like NewRangeScanner but the ranges it produceswill be offset by the given starting position, which is appropriate forsub-slices of a file, whereas NewRangeScanner assumes it is scanning anentire file.
func (*RangeScanner)Bytes¶
func (sc *RangeScanner) Bytes() []byte
Bytes returns the slice of the input buffer that is covered by the rangethat would be returned by Range.
func (*RangeScanner)Err¶
func (sc *RangeScanner) Err()error
Err can be called after Scan returns false to determine if the latest readresulted in an error, and obtain that error if so.
func (*RangeScanner)Range¶
func (sc *RangeScanner) Range()Range
Range returns a range that covers the latest token obtained after a callto Scan returns true.
func (*RangeScanner)Scan¶
func (sc *RangeScanner) Scan()bool
typeStaticCall¶
type StaticCall struct {NamestringNameRangeRangeArguments []ExpressionArgsRangeRange}StaticCall represents a function call that was extracted statically froman expression using ExprCall.
typeTraversal¶
type Traversal []Traverser
A Traversal is a description of traversing through a value through aseries of operations such as attribute lookup, index lookup, etc.
It is used to look up values in scopes, for example.
The traversal operations are implementations of interface Traverser.This is a closed set of implementations, so the interface cannot beimplemented from outside this package.
A traversal can be absolute (its first value is a symbol name) or relative(starts from an existing value).
funcTraversalJoin¶
TraversalJoin appends a relative traversal to an absolute traversal toproduce a new absolute traversal.
func (Traversal)IsRelative¶
IsRelative returns true if the receiver is a relative traversal, or falseotherwise.
func (Traversal)RootName¶
RootName returns the root name for a absolute traversal. Will panic ifcalled on a relative traversal.
func (Traversal)SimpleSplit¶
func (tTraversal) SimpleSplit()TraversalSplit
SimpleSplit returns a TraversalSplit where the name lookup is the absolutepart and the remainder is the relative part. Supported only forabsolute traversals, and will panic if applied to a relative traversal.
This can be used by applications that have a relatively-simple variablenamespace where only the top-level is directly populated in the scope, witheverything else handled by relative lookups from those initial values.
func (Traversal)SourceRange¶
SourceRange returns the source range for the traversal.
func (Traversal)TraverseAbs¶
func (tTraversal) TraverseAbs(ctx *EvalContext) (cty.Value,Diagnostics)
TraverseAbs applies the receiving traversal to the given eval context,returning the resulting value. This is supported only for absolutetraversals, and will panic if applied to a relative traversal.
func (Traversal)TraverseRel¶
TraverseRel applies the receiving traversal to the given value, returningthe resulting value. This is supported only for relative traversals,and will panic if applied to an absolute traversal.
typeTraversalSplit¶
TraversalSplit represents a pair of traversals, the first of which isan absolute traversal and the second of which is relative to the first.
This is used by calling applications that only populate prefixes of thetraversals in the scope, with Abs representing the part coming from thescope and Rel representing the remaining steps once that part isretrieved.
func (TraversalSplit)Join¶
func (tTraversalSplit) Join()Traversal
Join concatenates together the Abs and Rel parts to produce a singleabsolute traversal.
func (TraversalSplit)RootName¶
func (tTraversalSplit) RootName()string
RootName returns the root name for the absolute part of the split.
func (TraversalSplit)Traverse¶
func (tTraversalSplit) Traverse(ctx *EvalContext) (cty.Value,Diagnostics)
Traverse is a convenience function to apply TraverseAbs followed byTraverseRel.
func (TraversalSplit)TraverseAbs¶
func (tTraversalSplit) TraverseAbs(ctx *EvalContext) (cty.Value,Diagnostics)
TraverseAbs traverses from a scope to the value resulting from theabsolute traversal.
func (TraversalSplit)TraverseRel¶
func (tTraversalSplit) TraverseRel(valcty.Value) (cty.Value,Diagnostics)
TraverseRel traverses from a given value, assumed to be the result ofTraverseAbs on some scope, to a final result for the entire split traversal.
typeTraverseAttr¶
TraverseAttr looks up an attribute in its initial value.
func (TraverseAttr)SourceRange¶
func (tnTraverseAttr) SourceRange()Range
func (TraverseAttr)TraversalStep¶
func (tnTraverseAttr) TraversalStep(valcty.Value) (cty.Value,Diagnostics)
typeTraverseIndex¶
TraverseIndex applies the index operation to its initial value.
func (TraverseIndex)SourceRange¶
func (tnTraverseIndex) SourceRange()Range
func (TraverseIndex)TraversalStep¶
func (tnTraverseIndex) TraversalStep(valcty.Value) (cty.Value,Diagnostics)
typeTraverseRoot¶
TraverseRoot looks up a root name in a scope. It is used as the first stepof an absolute Traversal, and cannot itself be traversed directly.
func (TraverseRoot)SourceRange¶
func (tnTraverseRoot) SourceRange()Range
func (TraverseRoot)TraversalStep¶
func (tnTraverseRoot) TraversalStep(cty.Value) (cty.Value,Diagnostics)
TraversalStep on a TraverseName immediately panics, because absolutetraversals cannot be directly traversed.
typeTraverseSplat¶
TraverseSplat applies the splat operation to its initial value.
func (TraverseSplat)SourceRange¶
func (tnTraverseSplat) SourceRange()Range
func (TraverseSplat)TraversalStep¶
func (tnTraverseSplat) TraversalStep(valcty.Value) (cty.Value,Diagnostics)
Source Files¶
Directories¶
| Path | Synopsis |
|---|---|
Package hclsyntax contains the parser, AST, etc for HCL's native language, as opposed to the JSON variant. | Package hclsyntax contains the parser, AST, etc for HCL's native language, as opposed to the JSON variant. |
Package integrationtest is an internal package that contains some tests that attempt to exercise many HCL features together in realistic scenarios. | Package integrationtest is an internal package that contains some tests that attempt to exercise many HCL features together in realistic scenarios. |
Package json is the JSON parser for HCL. | Package json is the JSON parser for HCL. |