Documentation
¶
Overview ¶
Package token defines the lexical tokens of a YAML document, and the rules that type and convert a plain scalar.
Tokens ¶
A Token holds its Type, its Value -- the text with the syntax resolved, a quoted scalar without its quotes -- and the Position it starts at. It also records the offset its text ends at (Token.EndOffset) and five facts about the lines around it: the line it ends on, the line breaks taken by the comments above it and by the whitespace after it, whether a blank line stands above it, and whether a scanner cut it from a document (Token.FromSource).
The scanner in internal/scanner builds tokens with Make, Assemble and the MakeX constructors, such as MakeMappingValue. The parser builds the AST from them, and every node of package github.com/go-openapi/go-yaml/ast keeps one.
Scalars ¶
ScalarType resolves a plain scalar's text under a Schema: Schema12, the YAML 1.2 core schema and the default, or Schema11. Under 1.2 "0100" is the integer 100 and "yes" a string; under 1.1 they are 64 and true.
Once a scalar is typed, ParseBool, ParseInteger, ParseWholeNumber, ParseFloat, ParseBigInteger, ParseBigFloat and ParseTimestamp convert its text. KeyName names a mapping key by its resolved value, so the parser and the codec compare keys the same way.
Writing scalars back ¶
IsNeedQuoted reports whether a string needs quotes to read back as itself, and NeedsQuotedSpelling whether it needs double quotes and escapes. LiteralBlockHeader returns the block scalar header a multi-line string takes, or "" where it has no block form.
README.md in this directory describes the layout of a token, and why it fits in registers.
Index ¶
- Constants
- func CanonicalBase64(text string) string
- func DetectLineBreakCharacter(src string) string
- func FloatPastRange(text string, typ Type) (float64, bool)
- func IsNeedQuoted(value string) bool
- func KeyNameOfBigFloat(f *big.Float) string
- func KeyNameOfFloat(f float64, bitSize int) string
- func LiteralBlockHeader(value string) string
- func NeedsQuotedSpelling(value string) bool
- func ParseBigFloat(text string, typ Type) (*big.Float, bool)
- func ParseBigInteger(text string, typ Type) (*big.Int, bool)
- func ParseBool(text string) (bool, bool)
- func ParseFloat(text string, typ Type) (float64, bool)
- func ParseInteger(text string, typ Type) (any, bool)
- func ParseTimestamp(text string) (time.Time, bool)
- func ParseWholeNumber(text string, typ Type) (uint64, bool, bool)
- func TextBytes(s string) []byte
- func TrailingBreaksIn[T Text](org T) int
- type Character
- type CharacterType
- type Extent
- type Indicator
- type KeyKind
- type Lookback
- type Position
- type ReservedTagKeyword
- type Schema
- type Text
- type Token
- func Assemble(typ Type, value string, pos Position, ext Extent) Token
- func Comment(value string, org string, pos Position) *Token
- func Invalid(org string, pos Position) *Token
- func Make[T Text](value string, org T, pos Position) Token
- func MakeAlias[T Text](org T, pos Position) Token
- func MakeAnchor[T Text](org T, pos Position) Token
- func MakeCollectEntry[T Text](org T, pos Position) Token
- func MakeComment[T Text](value string, org T, pos Position) Token
- func MakeDirective[T Text](org T, pos Position) Token
- func MakeDocumentEnd[T Text](org T, pos Position) Token
- func MakeDocumentHeader[T Text](org T, pos Position) Token
- func MakeDoubleQuote[T Text](value string, org T, pos Position) Token
- func MakeFolded[T Text](value string, org T, pos Position) Token
- func MakeLiteral[T Text](value string, org T, pos Position) Token
- func MakeMappingEnd[T Text](org T, pos Position) Token
- func MakeMappingKey(pos Position) Token
- func MakeMappingStart[T Text](org T, pos Position) Token
- func MakeMappingValue(pos Position) Token
- func MakeMergeKey[T Text](org T, pos Position) Token
- func MakeSequenceEnd[T Text](org T, pos Position) Token
- func MakeSequenceEntry[T Text](org T, pos Position) Token
- func MakeSequenceStart[T Text](org T, pos Position) Token
- func MakeSingleQuote[T Text](value string, org T, pos Position) Token
- func MakeString[T Text](value string, org T, pos Position) Token
- func MakeTag[T Text](value string, org T, pos Position) Token
- func New(value string, org string, pos Position) *Token
- func Tag(value string, org string, pos Position) *Token
- func (t Token) BlankLineAbove() bool
- func (t Token) BreaksAfterLeading() int32
- func (t *Token) Bytes() []byte
- func (t *Token) Clone() *Token
- func (t Token) CommentBreaksAbove() int32
- func (t *Token) Detached() *Token
- func (t *Token) Dump(w io.Writer)
- func (t Token) EndLine() int32
- func (t Token) EndOffset() int
- func (t *Token) FromSource() bool
- func (t *Token) MarkFromSource()
- func (t *Token) SetBlankLineAbove(blank bool)
- func (t *Token) SetCommentBreaksAbove(n int32)
- func (t Token) TrailingBreaks() int32
- type Tokens
- type Type
Constants ¶
const ( // OffsetBits is the width of Position.Offset. A source must be shorter than 1<<OffsetBits bytes. OffsetBits = 40 // IndentBits is the width of Position.IndentNum. A line must be indented by fewer than 1<<IndentBits columns. IndentBits = 64 - OffsetBits )
const YAMLTagPrefix = "tag:yaml.org,2002:"
YAMLTagPrefix is the prefix the secondary tag handle "!!" expands to unless a "%TAG" directive gives it another, so "!!int" and "!<tag:yaml.org,2002:int>" name one tag and not two.
Variables ¶
This section is empty.
Functions ¶
func CanonicalBase64 ¶
CanonicalBase64 returns base64 text with the spaces, tabs and line breaks taken out, which RFC 2045 lets a writer put anywhere in it. Two "!!binary" scalars are one value when their canonical texts are equal.
func DetectLineBreakCharacter ¶
DetectLineBreakCharacter returns the line break src writes: "\r\n" where every break is one, "\r" where lone carriage returns outnumber line feeds, and "\n" otherwise, including for a text that holds no line break.
func FloatPastRange ¶
FloatPastRange returns the float64 a float scalar reads as where the decimal exponent of its value is past ±1000: an infinity of its sign for an overflow, as IEEE 754 rounds one, and zero for an underflow. It reports false where text is not a float of type typ, is zero, or is inside the range.
The exponent is the value's and not the one written: "0.001e1002" is 1e999, inside the range, and a 2,000-digit number written with a point is past it.
func IsNeedQuoted ¶
IsNeedQuoted reports whether value needs quotes to read back as the string it is, written as a plain scalar.
It quotes the empty string, a keyword or a number under either schema, a decimal with a leading zero, a timestamp or a clock time, a document marker, a leading indicator or blank, a leading "-" or "?" followed by a blank or by nothing, a trailing blank or ':', a '#' or a backslash anywhere, ": ", ":\t" or "- " inside, and a value NeedsQuotedSpelling reports.
func KeyNameOfBigFloat ¶
KeyNameOfBigFloat returns the name a float too wide or too small for a float64 takes, by the rule KeyNameOfFloat follows.
The digits come from big.Float.Text with 'g' and -1, the shortest text that reads back as the same value at the float's precision. Comparing two of them with big.Float.Cmp would not do: ParseBigFloat sizes the precision by the digits written, so one value written two ways can round apart.
func KeyNameOfFloat ¶
KeyNameOfFloat returns the name a float key takes, so that it can never spell an integer. bitSize is 32 for a float32 and 64 for a float64, as strconv.FormatFloat takes it.
strconv.FormatFloat with 'g' and -1 gives the shortest text that reads back as the same float, and ".0" goes on where that text holds no '.', 'e' or 'E'. So "1e3" is "1000.0", "1e30" stays "1e+30", and float32(0.5) and 0.5 are both "0.5": YAML has one float type, and Go's two widths name one key.
Expanding every float to decimal instead would write 1e300 as 301 characters and would print precision the value never had: 1e23 has no exact float64, and expanding it gives 99999999999999991611392 rather than the digits the document wrote. libfyaml 1.0.0a8 names a float this same way.
A negative zero is "0.0". YAML 1.2.2 section 10.2.1.4 gives zero one canonical form, and Go's == holds -0.0 and 0.0 as one map key. Named apart, the pair would pass the parser's duplicate check, and the decoder would merge them and drop the first value.
func LiteralBlockHeader ¶
LiteralBlockHeader returns the block scalar header value needs, or "" where value has no block scalar spelling.
A value holding a carriage return or a byte order mark has none, for two different reasons. YAML normalizes a stream's line breaks on read -- "\r\n" and a lone "\r" both become "\n" -- so a block scalar cannot carry a CR whatever it is written with. And nb-char excludes U+FEFF, so no block or plain scalar may hold one at all. Both have to be double-quoted, where each is an escape.
A value whose first line holding text starts with a space has none either. A reader takes the block's indentation from that line, so it would read "\n 0" written as "|-" over an empty line and " 0" as "\n0". Writing it would need an indentation indicator, which no writer here emits.
A value made only of line breaks keeps them with "|+": with no line of text, "|" and "|-" both read "".
func NeedsQuotedSpelling ¶
NeedsQuotedSpelling reports whether value holds a character that only a double-quoted scalar can carry, as an escape.
A carriage return is one: YAML normalizes a stream's line breaks on read, so "\r\n" and a lone "\r" both arrive as "\n" and no plain, single-quoted or block scalar keeps one. U+FEFF, the byte order mark, is another: nb-char excludes it, so no plain or block scalar may hold it.
The rest are the characters c-printable leaves out, which a YAML stream may not hold raw at all: the C0 controls but tab and line feed, DEL, the C1 controls but NEL, the surrogates, U+FFFE and U+FFFF, and a byte that is part of no character. Written raw, the document they are in does not read back.
Written as escapes inside a double-quoted scalar, all of them survive.
func ParseBigFloat ¶
ParseBigFloat returns text as a big.Float, for a real no float64 holds. It reports false where text is not a float, and where FloatPastRange reads it as an infinity or zero instead.
See ParseBigInteger for why a document may carry one.
func ParseBigInteger ¶
ParseBigInteger returns text as a big.Int, for a whole number no native type holds. It reports false where text is not an integer of type typ.
The scanner types a scalar by the grammar its text follows and never by whether a native type has room for it, so a document may carry an integer wider than int64 or uint64. YAML 1.2 calls the type "arbitrary sized finite mathematical integers", and ParseBigInteger reads one that outgrows ParseInteger exactly.
func ParseBool ¶
ParseBool returns what a boolean scalar means, and reports false where text is not one.
Do not use strconv.ParseBool for a YAML boolean: it reads "1", "t" and "T" as true, which YAML resolves to no boolean, and rejects "yes", "y" and "on", which YAML 1.1 reads as true.
ParseBool reads both schemas' spellings and needs no schema: no spelling is true under one and false under the other, and a scalar reaches it only once a schema has typed it BoolType.
func ParseFloat ¶
ParseFloat returns what a float scalar means, and reports false where text is not a float of type typ. See ParseInteger for typ and for when the conversion happens.
func ParseInteger ¶
ParseInteger returns what an integer scalar means: an int64 where the text carries a sign, a uint64 where it does not. It reports false where text is not an integer of type typ.
typ is the token's type, which gives the base the digits are written in. The scanner types a scalar without converting it, and ParseInteger converts it when a caller asks, so a number nothing reads is never converted.
func ParseTimestamp ¶
ParseTimestamp reads text as a timestamp of the YAML 1.1 type tag:yaml.org,2002:timestamp.
It accepts what the regular expression at https://yaml.org/type/timestamp.html accepts, and nothing else:
[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] (a date) [0-9][0-9][0-9][0-9]-[0-9][0-9]?-[0-9][0-9]? (a date and a time) ([Tt]|[ \t]+)[0-9][0-9]?:[0-9][0-9]:[0-9][0-9](\.[0-9]*)? ([ \t]*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?))?
So a date alone takes two-digit month and day fields, and a date with a time may take one-digit ones. The zone may be written "-5", "-05" or "-05:00", and any run of spaces or tabs may stand before it.
The fraction of a second may be a dot with no digit after it, as in "21:59:43.Z". ParseTimestamp keeps the first nine digits of a fraction and drops the rest.
Each field must also be in range: a month from 1 to 12, a day the month has, an hour below 24, and a minute or second below 60. A timestamp with no zone, or with "Z", is in UTC. One with an offset is in a time.FixedZone of that offset, whatever the local zone.
Under YAML 1.1, the parser resolves a plain scalar ParseTimestamp accepts to a timestamp. The decoder reads a "!!timestamp" scalar or a time.Time destination with ParseTimestamp. IsNeedQuoted quotes a string ParseTimestamp accepts, so the string reads back as a string.
func ParseWholeNumber ¶
ParseWholeNumber reads text as a whole number and returns how large it is and whether it is negative, or false where text is not an integer of type typ or is one no machine word holds.
It returns what ParseInteger returns, without the interface. ParseInteger returns an int64 or a uint64 in an any, which boxes every integer of a document, so a caller that writes the digits back out uses this one. README.md in this directory gives the cost of the boxing.
The magnitude is returned rather than the value so that the smallest int64 fits: its magnitude is 1<<63, which int64 cannot hold.
func TextBytes ¶
TextBytes returns s as bytes without copying it.
The bytes are the string's own. A Go string is immutable, and a token's text is usually a window into the document rather than a copy of it, so writing through them corrupts the value and every other value cut from the same source. Read them. Copy them before keeping them past the document.
func TrailingBreaksIn ¶
TrailingBreaksIn counts the line breaks in the blank run org ends with: what stands between the token's last line and whatever is read next.
A scanner that tracks the line its cursor is on needs only this, since the token's text ends that many breaks above the cursor. Reading the whole origin, as MeasureOrigin does, serves a caller with no cursor to count back from.
Types ¶
type Character ¶
type Character byte
Character is a byte that opens, closes or separates a YAML construct.
const ( // SequenceEntryCharacter is '-', which opens an entry of a block sequence. SequenceEntryCharacter Character = '-' // MappingKeyCharacter is '?', which opens an explicit mapping key. MappingKeyCharacter Character = '?' // MappingValueCharacter is ':', which separates a mapping key from its value. MappingValueCharacter Character = ':' // CollectEntryCharacter is ',', which separates two entries of a flow collection. CollectEntryCharacter Character = ',' // SequenceStartCharacter is '[', which opens a flow sequence. SequenceStartCharacter Character = '[' // SequenceEndCharacter is ']', which closes a flow sequence. SequenceEndCharacter Character = ']' // MappingStartCharacter is '{', which opens a flow mapping. MappingStartCharacter Character = '{' // MappingEndCharacter is '}', which closes a flow mapping. MappingEndCharacter Character = '}' // CommentCharacter is '#', which opens a comment. CommentCharacter Character = '#' // AnchorCharacter is '&', which opens an anchor. AnchorCharacter Character = '&' // AliasCharacter is '*', which opens an alias. AliasCharacter Character = '*' // TagCharacter is '!', which opens a tag. TagCharacter Character = '!' // LiteralCharacter is '|', which opens a literal block scalar. LiteralCharacter Character = '|' // FoldedCharacter is '>', which opens a folded block scalar. FoldedCharacter Character = '>' // SingleQuoteCharacter is the single quote that opens and closes a single-quoted scalar. SingleQuoteCharacter Character = '\'' // DoubleQuoteCharacter is the double quote that opens and closes a double-quoted scalar. DoubleQuoteCharacter Character = '"' // DirectiveCharacter is '%', which opens a directive. DirectiveCharacter Character = '%' // SpaceCharacter is the space, which separates tokens and indents a block. SpaceCharacter Character = ' ' // LineBreakCharacter is the line feed, which ends a line. LineBreakCharacter Character = '\n' )
type CharacterType ¶
type CharacterType int
CharacterType is the class of character a token is written with. See Type.CharacterType.
const ( // CharacterTypeIndicator marks an indicator, such as ':' or '['. CharacterTypeIndicator CharacterType = iota // CharacterTypeMiscellaneous marks any other character, as a scalar is. CharacterTypeMiscellaneous // CharacterTypeEscaped marks an escaped character. CharacterTypeEscaped // CharacterTypeInvalid marks text the scanner could not read. CharacterTypeInvalid )
func (CharacterType) String ¶
func (c CharacterType) String() string
String returns the name of c, such as "Indicator", or "" for a value outside the constants.
type Extent ¶
type Extent struct {
// End is the byte just past the token's text, so that src[Offset:End] is
// what the document wrote the token as.
End int
// EndLine is the line the token's text ends on. A token written on one
// line ends on the line it starts on.
EndLine int
// Trailing counts the line breaks between the token's last line and
// whatever the scanner reads next.
Trailing int
}
Extent is how far a token reaches through the source, past the offset its Position gives.
A scanner has all three as it cuts a token and passes them to Assemble. A caller holding only the text the token was written as reads them with MeasureOrigin.
func MeasureOrigin ¶
MeasureOrigin reads a token's origin once and returns the extent it gives.
org is everything the scanner read since the previous token: the blanks in front of the token, its text, and the blanks after it. MeasureOrigin walks it three times: forward over the leading blanks, backward over the trailing ones counting their breaks, and across the text between them.
type Indicator ¶
type Indicator int
Indicator is the kind of syntax an indicator character opens, as YAML 1.2.2 section 5.3 groups them.
const ( // NotIndicator marks a token that is not an indicator. NotIndicator Indicator = iota // BlockStructureIndicator marks block structure: '-', '?', ':'. BlockStructureIndicator // FlowCollectionIndicator marks a flow collection: '[', ']', '{', '}', ','. FlowCollectionIndicator // CommentIndicator marks a comment: '#'. CommentIndicator // NodePropertyIndicator marks a node property: '!', '&', '*'. NodePropertyIndicator // BlockScalarIndicator marks a block scalar: '|', '>'. BlockScalarIndicator // QuotedScalarIndicator marks a quoted scalar: a single or a double quote. QuotedScalarIndicator // DirectiveIndicator marks a directive: '%'. DirectiveIndicator // InvalidUseOfReservedIndicator marks a character YAML reserves and does not allow to start a plain scalar: '@', '`'. InvalidUseOfReservedIndicator )
type KeyKind ¶
type KeyKind uint8
KeyKind is the type a mapping key resolves to.
YAML 1.2.2 §3.2.1.1 makes two keys equal when they resolve to the same node, so a key's identity is its type and its value and not the characters the document wrote: "7" and "007" are one integer written twice and so one key, where "1" and "1.0" are an integer and a float and so two.
const ( // KeyOther is a scalar the schema did not resolve, or a node that is not a // scalar at all. KeyOther KeyKind = iota KeyString KeyNull KeyBool KeyInt KeyFloat // KeyTimestamp is a "!!timestamp", named in RFC 3339 and compared as its // instant in UTC. It has a kind of its own so the string // "2001-12-14T00:00:00Z" and the timestamp written "2001-12-14" stay two // keys. KeyTimestamp // KeyBinary is a "!!binary", named by its canonical base64 text // ([CanonicalBase64]). YAML distinguishes binary data from a string, so "!!binary AA==" and the string // "AA==" are two keys. KeyBinary )
func KeyName ¶
KeyName returns the canonical text a scalar addresses a mapping entry by, and the type it resolved to.
The name is the type's own spelling and not the document's. An integer is written in decimal whatever base it was read from, so "0x10" and "007" name 16 and 7; every spelling of a null names "null" and of a boolean "true" or "false".
A float name always carries a '.' or an exponent, so no float spells an integer: "1" and "1.0" are two keys with two names.
The parser calls KeyName to compare keys, and github.com/go-openapi/go-yaml/codec to name an entry in JSON or in a string-keyed map, so both name a key the same way.
A name that is the text itself is returned as the text, so a key spelled the way its type spells it -- which is nearly every key of nearly every document -- costs no allocation and stays a window into the source.
type Lookback ¶
type Lookback struct {
// contains filtered or unexported fields
}
Lookback derives two facts about each token from the tokens read before it: whether the author left a blank line above it, and how many line breaks the comments above it take up.
Both depend only on the last two tokens, on whether the scalar before those is a block header's content, and on a running count of the breaks in the comments just read. Lookback keeps those four and updates them as each token goes past, so a stream is read once, forward, and no token already emitted is held or read again.
type Position ¶
Position records where a token starts in the source.
Line and Column count from 1, in characters, as YAML measures indentation. Offset counts from 0, in bytes, so src[Offset:] starts with the token, and a caret drawn from Line and Column lands on its first character.
Offset can start earlier than the token's text for two kinds of token: block scalar content, and the Invalid token an error carries. README.md in this directory gives the counts.
Line and Column are int32. Offset takes 40 bits and IndentNum 24, packed in one word, so Offset reaches 1 TiB and IndentNum 16 M columns. A token holds its Position by value, so the width of each number adds to the token's width.
func At ¶
At returns the position at line, column, offset and indentNum. A composite literal cannot set Offset and IndentNum, which share a packed field.
Line and Column narrow to int32. The scanner refuses a source with more lines than that holds.
type ReservedTagKeyword ¶
type ReservedTagKeyword string
ReservedTagKeyword is a tag of the YAML type repository, in its "!!" shorthand, such as "!!int".
const ( // IntegerTag is "!!int". IntegerTag ReservedTagKeyword = "!!int" // FloatTag is "!!float". FloatTag ReservedTagKeyword = "!!float" // NullTag is "!!null". NullTag ReservedTagKeyword = "!!null" // SequenceTag is "!!seq". SequenceTag ReservedTagKeyword = "!!seq" // MappingTag is "!!map". MappingTag ReservedTagKeyword = "!!map" // StringTag is "!!str". StringTag ReservedTagKeyword = "!!str" // BinaryTag is "!!binary". BinaryTag ReservedTagKeyword = "!!binary" // OrderedMapTag is "!!omap". OrderedMapTag ReservedTagKeyword = "!!omap" // SetTag is "!!set". SetTag ReservedTagKeyword = "!!set" // TimestampTag is "!!timestamp". TimestampTag ReservedTagKeyword = "!!timestamp" // BooleanTag is "!!bool". BooleanTag ReservedTagKeyword = "!!bool" // MergeTag is "!!merge". MergeTag ReservedTagKeyword = "!!merge" )
func ReservedTagOf ¶
func ReservedTagOf(uri string) (ReservedTagKeyword, bool)
ReservedTagOf returns the reserved tag a URI names, or false for every other URI: a tag the document defines, or a tag of another namespace.
A document usually writes the shorthand "!!int" and means tag:yaml.org,2002:int. Expanding the shorthand before matching here resolves both spellings to one tag, and lets a "%TAG !!" line that repoints the handle take "!!int" out of this namespace.
type Schema ¶
type Schema uint8
Schema is the tag resolution a plain scalar is read against.
YAML resolves an untagged plain scalar by matching its text against the schema's table. Under Schema12 "0100" is the integer 100 and "no" a string; under Schema11 they are 64 and false. github.com/go-openapi/go-yaml/internal/scanner.Scanner.SetSchema sets the schema a scanner reads with.
const ( // Schema12 is the YAML 1.2 core schema, YAML 1.2.2 section 10.3.2. It is the zero value, so a scalar is // read against 1.2 unless a "%YAML 1.1" directive or an option sets Schema11. Schema12 Schema = iota // Schema11 is YAML 1.1's resolution, which a document may ask for with a // "%YAML 1.1" directive. // // It adds YAML 1.1's spellings of true and false -- y, n, yes, no, on, off // -- the "_" digit separator, binary written "0b1010" and octal written // with a leading zero, and it drops 1.2's "0o" prefix, its unsigned // exponent and its exponent without a fraction. // // Base 60 -- "190:20:30", which is 685230 -- is here too, read group by // group since no strconv base reaches 60. Schema11 )
type Text ¶
Text holds what a token was written as: the document's own string, or the buffer a scanner filled reading it.
The token keeps neither. The functions that take a Text measure it, so a scanner passes its buffer as it stands: converting it to a string would copy the bytes, an allocation for every token too long for the stack.
type Token ¶
type Token struct {
// Value is the token's text with the syntax resolved: a quoted scalar without its quotes and escapes, a block
// scalar folded and chomped, a plain scalar as written.
Value string
// Position records where the token starts in the source.
Position Position
// Type identifies what the token is.
Type Type
// contains filtered or unexported fields
}
Token is one lexical token of a YAML document.
It takes 56 bytes and passes in eight registers. README.md in this directory describes the layout, and why a new field belongs in spans.
func Assemble ¶
Assemble builds a token from parts a caller already holds, reading nothing.
The scanner has a token's type, value, position and extent by the time it cuts it, so it has no origin to measure. MeasureOrigin measures one, and Make calls both.
func Comment ¶
Comment returns a pointer to the token MakeComment returns.
func Invalid ¶
Invalid returns the token a scanner stopped on, holding the text it could not read.
The token carries no message: the scanner's error does, so no token spends room on one.
func Make ¶
Make returns the token for value at pos, typed as Schema12 resolves a plain scalar: a keyword, a number or a string. Its end is measured from org, the text the scanner read for it.
Make returns the token as a value, so a caller that keeps its tokens in a slice allocates none.
func MakeAlias ¶
MakeAlias returns the '*' of an alias, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeAnchor ¶
MakeAnchor returns the '&' of an anchor, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeCollectEntry ¶
MakeCollectEntry returns the ',' between two entries of a flow collection, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeComment ¶
MakeComment returns a comment holding value, the text after its '#', at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeDirective ¶
MakeDirective returns the '%' of a directive, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeDocumentEnd ¶
MakeDocumentEnd returns the '...' that ends a document, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeDocumentHeader ¶
MakeDocumentHeader returns the '---' that opens a document, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeDoubleQuote ¶
MakeDoubleQuote returns a double-quoted scalar holding value, its escapes resolved, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeFolded ¶
MakeFolded returns the '>' header of a folded block scalar, holding value, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeLiteral ¶
MakeLiteral returns the '|' header of a literal block scalar, holding value, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeMappingEnd ¶
MakeMappingEnd returns the '}' that closes a flow mapping, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeMappingKey ¶
MakeMappingKey returns the '?' of an explicit mapping key, at pos. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeMappingStart ¶
MakeMappingStart returns the '{' that opens a flow mapping, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeMappingValue ¶
MakeMappingValue returns the ':' of a mapping entry, at pos. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeMergeKey ¶
MakeMergeKey returns the '<<' merge key, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeSequenceEnd ¶
MakeSequenceEnd returns the ']' that closes a flow sequence, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeSequenceEntry ¶
MakeSequenceEntry returns the '-' of a block sequence entry, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeSequenceStart ¶
MakeSequenceStart returns the '[' that opens a flow sequence, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeSingleQuote ¶
MakeSingleQuote returns a single-quoted scalar holding value, its quotes resolved, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeString ¶
MakeString returns a plain scalar holding value, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func MakeTag ¶
MakeTag returns a tag holding value, at pos, its end measured from org. It returns the token as a value: a scanner copies it into a slice without an allocation.
func (Token) BlankLineAbove ¶
BlankLineAbove reports whether the author left an empty line above this token. The renderer writes one back there, so a document keeps the spacing it was written with.
func (Token) BreaksAfterLeading ¶
BreaksAfterLeading counts the line breaks from the token's first character to the end of the whitespace following it. It is Token.EndLine less Position.Line, plus Token.TrailingBreaks.
func (*Token) Bytes ¶
Bytes returns t's value as bytes, without copying it. See TextBytes for what a caller may do with them.
func (*Token) Clone ¶
Clone returns a copy of t, or nil for a nil t. The copy keeps Token.FromSource; see Token.Detached.
func (Token) CommentBreaksAbove ¶
CommentBreaksAbove counts the line breaks taken up by the comments written immediately above this token. A document rendered without those comments still has to leave the lines they stood on, or what was written under them runs into what was written before.
func (*Token) Detached ¶
Detached returns a copy of t that claims no document.
A token cut from a source carries the offsets it was read at, and a verbatim rendering writes it by copying those bytes back. A copy of a node put somewhere else in the tree must not do that: the bytes at those offsets stand where the document wrote the original, and the copy of the source runs forward past them once. Detached clears Token.FromSource so the node it belongs to is laid out where it was put instead. See [ast.Clone].
func (Token) EndLine ¶
EndLine is the line the token's text ends on, counting from 1 as Position.Line does. A token written on one line ends on the line it starts on, so EndLine equals Position.Line for all but block scalars, multi-line quoted scalars and comments.
The scanner records it as it builds the token, so no caller counts it again. Leading and trailing whitespace does not count: those breaks belong to the gap around the token.
A token the parser makes up for a value the document leaves out ends where it starts, having no text in the document at all.
func (Token) EndOffset ¶
EndOffset returns the byte just past the token's text, so src[Offset:EndOffset] holds the text the document wrote, without the whitespace before it. A token the parser builds for a value the document leaves out ends where it starts.
func (*Token) FromSource ¶
FromSource reports whether the scanner cut this token from a document.
A token built by hand or by the encoder answers false, and it cannot be told apart any other way: github.com/go-openapi/go-yaml/codec.ValueToNode gives every node a token at line 1, column 1, offset 0, which is exactly what a real token at the start of a document reports. A reader that writes a document back as it was written needs to know which of the two it holds.
func (*Token) MarkFromSource ¶
func (t *Token) MarkFromSource()
MarkFromSource records that this token was cut from a document.
The scanner calls it at the one place every token it reads passes through. Nothing else should: a token that claims a source it does not have is one a verbatim reader will try to place by a position that means nothing.
func (*Token) SetBlankLineAbove ¶
SetBlankLineAbove records that the author left an empty line above this token.
func (*Token) SetCommentBreaksAbove ¶
SetCommentBreaksAbove records the line breaks the comments above this token take up.
func (Token) TrailingBreaks ¶
TrailingBreaks counts the line breaks the whitespace after the token takes up, before whatever is written next.
Token.EndLine leaves them out: they are the gap after the token. Add TrailingBreaks to EndLine for the line the gap ends on, and test it against zero to know whether a line break follows the token.
type Tokens ¶
type Tokens []*Token
Tokens is a sequence of tokens, in the order the scanner cut them.
type Type ¶
type Type uint8
Type identifies what a token is.
There are 34 types, so one byte holds any, and Token spends one byte on its type.
const ( // UnknownType is the zero Type, which no token the scanner cuts carries. UnknownType Type = iota // DocumentHeaderType marks the '---' that opens a document. DocumentHeaderType // DocumentEndType marks the '...' that ends a document. DocumentEndType // SequenceEntryType marks the '-' of a block sequence entry. SequenceEntryType // MappingKeyType marks the '?' of an explicit mapping key. MappingKeyType // MappingValueType marks the ':' of a mapping entry. MappingValueType // MergeKeyType marks the '<<' merge key, where the merge key is in force. MergeKeyType // CollectEntryType marks the ',' between two entries of a flow collection. CollectEntryType // SequenceStartType marks the '[' that opens a flow sequence. SequenceStartType // SequenceEndType marks the ']' that closes a flow sequence. SequenceEndType // MappingStartType marks the '{' that opens a flow mapping. MappingStartType // MappingEndType marks the '}' that closes a flow mapping. MappingEndType // CommentType marks a comment. CommentType // AnchorType marks the '&' of an anchor. AnchorType // AliasType marks the '*' of an alias. AliasType // TagType marks a tag. TagType // LiteralType marks the '|' header of a literal block scalar. LiteralType // FoldedType marks the '>' header of a folded block scalar. FoldedType // SingleQuoteType marks a single-quoted scalar. SingleQuoteType // DoubleQuoteType marks a double-quoted scalar. DoubleQuoteType // DirectiveType marks the '%' of a directive. DirectiveType // NullType marks a plain scalar that resolves to null: "null" or "~", in any case the schema allows. NullType // ImplicitNullType marks a null the document left out, as in "e:". Its token has no text in the document, // and a writer writes nothing for it. ImplicitNullType // InfinityType marks a plain scalar that resolves to an infinity, such as ".inf". InfinityType // NanType marks a plain scalar that resolves to not-a-number, ".nan". NanType // IntegerType marks a plain scalar that resolves to a decimal integer. IntegerType // BinaryIntegerType marks a plain scalar that resolves to an integer written in base 2, "0b1010". BinaryIntegerType // OctetIntegerType marks a plain scalar that resolves to an integer written in base 8, "0o17", or "017" under 1.1. OctetIntegerType // HexIntegerType marks a plain scalar that resolves to an integer written in base 16, "0x1F". HexIntegerType // FloatType marks a plain scalar that resolves to a float. FloatType // StringType marks a plain scalar that resolves to a string. StringType // BoolType marks a plain scalar that resolves to a boolean. BoolType // InvalidType marks text the scanner could not read as any token. InvalidType )
func FloatBase ¶
FloatBase returns the type whose spelling rules a float scalar's text follows, and false where schema reads it as no number at all.
Like IntegerBase, it reads the text under the document's schema. It takes the three number families a float tag may stand over: FloatType, the InfinityType and NanType spellings, and an integer type, since a whole number is a real number. "!!float 017" is 15.0 under 1.1 and 17.0 under 1.2, each following the base its own schema gave the digits.
func IntegerBase ¶
IntegerBase returns the type whose base an integer scalar's digits are written in, and false where schema reads them as no whole number.
The answer depends on schema, the one the document is read under: "017" is OctetIntegerType under 1.1 and IntegerType under 1.2, and "0b101" is BinaryIntegerType under 1.1 and StringType under 1.2.
IntegerBase reads the text, not the type the scanner gave the token, so a quoted and a plain scalar holding the same characters get the same answer. YAML 1.2.2 section 3.3.2 makes `!!int "017"` and `!!int 017` one node, and both read as 15 under 1.1.
Use it with ParseWholeNumber or ParseBigInteger, which read the digits in the base the type names. Do not use strconv.ParseInt with base 0: it reads Go's integer literals, which take a sign on a hex number, a capital "X", a "0b" prefix and "_" separators, none of which the 1.2 core schema writes.
func ScalarType ¶
ScalarType returns the type schema resolves a plain scalar's text to: the type of a reserved keyword, of a number, or StringType where the text is neither.
A quoted scalar is a string whatever it spells, so call ScalarType only for a plain scalar.
func (Type) CharacterType ¶
func (t Type) CharacterType() CharacterType
CharacterType returns the class of character a token of type t is written with. It follows from the type, as Type.Indicator does.
func (Type) Indicator ¶
Indicator returns the indicator a token of type t is, or NotIndicator where it is not one.
A token's indicator follows from its type, so the token does not record it. TestEveryTypeHasAnIndicator checks every type.
func (Type) IsInteger ¶
IsInteger reports whether a token of type t holds a whole number, in whatever base it was written: 16 for HexIntegerType, 8 for OctetIntegerType, 2 for BinaryIntegerType and 10 for IntegerType.
ScalarType picks which of the four a plain scalar is, under the schema the document is read with, and ParseWholeNumber reads the digits back in that base. Check IsInteger before taking the base from a type that came from elsewhere, such as a tag.