Documentation
¶
Overview ¶
Package token provides a memory-efficient representation of a token tree stream for the Protobuf IDL.
Token Trees ¶
Tokens in Protocompile are trees: a token may "contain" a range of other tokens. For example, the tokens between matched braces { } are contained within the braces, accessible via Token.Children. This simplifies parsing, since it moves the tricky work of matching braces out of the parser and into the lexer. It is also use for other sequences of tokens that are better manipulated as a single token, such as juxtaposed strings that are automatically concatenated.
Synthetic Tokens ¶
To support post-parse modification, this library distinguishes between natural [Token]s (those created by a parse operation) and synthetic [Token]s (those created programmatically to modify/build an AST).
Synthetic tokens have a few important differences from ordinary tokens, the most important of which is that they do not appear in the token stream (so Stream.Cursor won't find them) and they do not have [source.Span]s, so they cannot be used in diagnostics (Span() will return the zero source.Span).
Index ¶
- func ClearMeta[M tokenmeta.Meta](token Token)
- func Fuse(open, close Token)
- func GetMeta[M tokenmeta.Meta](token Token) *M
- func MutateMeta[M tokenmeta.Meta](token Token) *M
- type Cursor
- func (c *Cursor) Clone() *Cursor
- func (c *Cursor) Context() *Stream
- func (c *Cursor) Done() bool
- func (c *Cursor) IsSynthetic() bool
- func (c *Cursor) Mark() CursorMark
- func (c *Cursor) NewLinesBetween(a, b Token, limit int) int
- func (c *Cursor) Next() Token
- func (c *Cursor) NextSkippable() Token
- func (c *Cursor) Peek() Token
- func (c *Cursor) PeekPrev() Token
- func (c *Cursor) PeekPrevSkippable() Token
- func (c *Cursor) PeekSkippable() Token
- func (c *Cursor) Prev() Token
- func (c *Cursor) PrevSkippable() Token
- func (c *Cursor) Rest() iter.Seq[Token]
- func (c *Cursor) RestSkippable() iter.Seq[Token]
- func (c *Cursor) Rewind(mark CursorMark)
- func (c *Cursor) SeekToEnd() (Token, source.Span)
- type CursorMark
- type Escape
- type ID
- type Kind
- type NumberToken
- func (n NumberToken) Base() byte
- func (n NumberToken) ExpBase() int
- func (n NumberToken) Exponent() source.Span
- func (n NumberToken) Float() (v float64, exact bool)
- func (n NumberToken) HasSeparators() bool
- func (n NumberToken) Int() (v uint64, exact bool)
- func (n NumberToken) IsFloat() bool
- func (n NumberToken) IsLegacyOctal() bool
- func (n NumberToken) IsValid() bool
- func (n NumberToken) Mantissa() source.Span
- func (n NumberToken) Prefix() source.Span
- func (n NumberToken) Suffix() source.Span
- func (n NumberToken) Token() Token
- func (n NumberToken) Value() *decimal.Decimal
- type Stream
- func (s *Stream) All() iter.Seq[Token]
- func (s *Stream) Around(offset int) (Token, Token)
- func (s *Stream) AssertEmpty()
- func (s *Stream) Cursor() *Cursor
- func (s *Stream) Freeze()
- func (s *Stream) FromID(id uint64, want any) any
- func (s *Stream) NewFused(openTok, closeTok Token, children ...Token)
- func (s *Stream) NewIdent(name string) Token
- func (s *Stream) NewPunct(text string) Token
- func (s *Stream) NewString(text string) Token
- func (s *Stream) Push(length int, kind Kind) Token
- func (s *Stream) PushKeyword(length int, kind Kind, kw keyword.Keyword) Token
- type StringToken
- func (s StringToken) Escapes() seq.Indexer[Escape]
- func (s StringToken) HasEscapes() bool
- func (s StringToken) IsConcatenated() bool
- func (s StringToken) IsPure() bool
- func (s StringToken) Prefix() source.Span
- func (s StringToken) Quotes() (open, close source.Span)
- func (s StringToken) RawContent() source.Span
- func (s StringToken) Text() string
- func (s StringToken) Token() Token
- type Token
- func (t Token) AsNumber() NumberToken
- func (t Token) AsString() StringToken
- func (t Token) Children() *Cursor
- func (t Token) IsLeaf() bool
- func (t Token) IsSynthetic() bool
- func (t Token) Keyword() keyword.Keyword
- func (t Token) Kind() Kind
- func (t Token) LeafSpan() source.Span
- func (t Token) Name() string
- func (t Token) Next() Token
- func (t Token) Prev() Token
- func (t Token) SetKind(k Kind)
- func (t Token) Span() source.Span
- func (t Token) StartEnd() (start, end Token)
- func (t Token) String() string
- func (t Token) SyntheticChildren(i, j int) *Cursor
- func (t Token) Text() string
- type Value
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClearMeta ¶
ClearMeta clears the associated literal value of a token.
Panics if the given token is zero, or if the token is natural and the stream is frozen.
Note: this function wants to be a method of Token, but cannot because it is generic.
func Fuse ¶
func Fuse(open, close Token)
Fuse marks a pair of tokens as their respective open and close.
If open or close are synthetic or not currently a leaf, have different contexts, or are part of a frozen Stream, this function panics.
func GetMeta ¶
GetMeta returns the metadata value associated with this token. This function cannot be called outside of protocompile.
Note: this function wants to be a method of Token, but cannot because it is generic.
func MutateMeta ¶
MutateMeta is like GetMeta, but it first initializes the meta value.
Panics if the given token is zero, or if the token is natural and the stream is frozen.
Note: this function wants to be a method of Token, but cannot because it is generic.
Types ¶
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor is an iterator-like construct for looping over a token tree. Unlike a plain range func, it supports peeking.
func NewCursorAt ¶
NewCursorAt returns a new cursor at the given token.
Panics if the token is zero or synthetic.
func NewSliceCursor ¶
NewSliceCursor returns a new cursor over a slice of token IDs in the given context.
func (*Cursor) Clone ¶
Clone returns a copy of this cursor, which allows performing operations on it without mutating the original cursor.
func (*Cursor) IsSynthetic ¶
IsSynthetic returns whether this is a cursor over synthetic tokens.
func (*Cursor) Mark ¶
func (c *Cursor) Mark() CursorMark
Mark makes a mark on this cursor to indicate a place that can be rewound to.
func (*Cursor) NewLinesBetween ¶
NewLinesBetween counts the number of \n characters between the end of token.Token a and the start of b, up to the limit.
The final rune of a is included in this count, since comments may end in a \n rune.
func (*Cursor) NextSkippable ¶
NextSkippable returns the next skippable token in the sequence, and advances the cursor.
func (*Cursor) Peek ¶
Peek returns the next token in the sequence, if there is one. This automatically skips past skippable tokens.
Returns the zero token if this cursor is at the end of the stream.
func (*Cursor) PeekPrev ¶
PeekPrev returns the previous token in the sequence, if there is one. This automatically skips past skippable tokens.
Returns the zero token if this cursor is at the start of the stream.
func (*Cursor) PeekPrevSkippable ¶
PeekPrevSkippable returns the token before the current token in the sequence, if there is one. This may return a skippable token.
Returns the zero token if this cursor is at the beginning of the stream.
func (*Cursor) PeekSkippable ¶
PeekSkippable returns the current token in the sequence, if there is one. This may return a skippable token.
Returns the zero token if this cursor is at the end of the stream.
func (*Cursor) PrevSkippable ¶
PrevSkippable returns the previous skippable token in the sequence, and decrements the cursor.
func (*Cursor) Rest ¶
Rest returns an iterator over the remaining tokens in the cursor.
Note that breaking out of a loop over this iterator, and starting a new loop, will resume at the iteration that was broken at. E.g., if we break out of a loop over c.Iter at token tok, and start a new range over c.Iter, the first yielded token will be tok.
func (*Cursor) RestSkippable ¶
RestSkippable is like Cursor.Rest. but it yields skippable tokens, too.
Note that breaking out of a loop over this iterator, and starting a new loop, will resume at the iteration that was broken at. E.g., if we break out of a loop over c.Iter at token tok, and start a new range over c.Iter, the first yielded token will be tok.
func (*Cursor) Rewind ¶
func (c *Cursor) Rewind(mark CursorMark)
Rewind moves this cursor back to the position described by Rewind.
Panics if mark was not created using this cursor's Mark method.
type CursorMark ¶
type CursorMark struct {
// contains filtered or unexported fields
}
CursorMark is the return value of Cursor.Mark, which marks a position on a Cursor for rewinding to.
type Escape ¶
type Escape struct {
source.Span
// If Rune is zero, this escape represents a raw byte rather than a
// Unicode character.
Rune rune
Byte byte
}
Escape is an escape inside of a StringToken. See StringToken.Escapes.
type ID ¶
ID is the raw ID of a Token separated from its [Context].
The zero value is reserved as a nil representation. All other values are opaque.
type Kind ¶
type Kind byte
Kind identifies what kind of token a particular Token is.
const ( Unrecognized Kind = iota // Unrecognized garbage in the input file. Space // Non-comment contiguous whitespace. Comment // A single comment. Ident // An identifier, which may be a soft keyword. String // A string token. May be a non-leaf for non-contiguous quoted strings. Number // A run of digits that is some kind of number. Keyword // A hard keyword. May be a non-leaf for delimiters like {}. )
func (Kind) IsSkippable ¶
IsSkippable returns whether this is a token that should be examined during syntactic analysis.
type NumberToken ¶
NumberToken provides access to detailed information about a Number.
func (NumberToken) ExpBase ¶
func (n NumberToken) ExpBase() int
ExpBase returns this number's exponent base, if this number has an exponent; returns 1 if it has no exponent.
func (NumberToken) Exponent ¶
func (n NumberToken) Exponent() source.Span
Exponent returns the exponent digits for this literal, i.e., everything after the exponent letter. Returns the zero span if there is no exponent.
For example, for 0x123.456p-789, this will be -789.
func (NumberToken) Float ¶
func (n NumberToken) Float() (v float64, exact bool)
Float converts this value into a 64-bit float.
Returns whether the conversion was exact.
func (NumberToken) HasSeparators ¶
func (n NumberToken) HasSeparators() bool
HasSeparators returns whether this token contains thousands separator runes.
func (NumberToken) Int ¶
func (n NumberToken) Int() (v uint64, exact bool)
Int converts this value into a 64-bit unsigned integer.
A literal carries no sign — a leading `-` is a separate prefix expression — so this is a magnitude. A value that is not whole is rounded to nearest, with a half going away from zero, matching decimal.Decimal.Int: `1.5` gives 2 and `2.9` gives 3.
Returns whether the conversion was exact, which is false both for a value that had to be rounded and for one too large to represent.
func (NumberToken) IsFloat ¶
func (n NumberToken) IsFloat() bool
IsFloat returns whether this token can only be used as a float literal (even if it has integer value).
A `.` or an exponent makes a literal a float, which is what protoc enforces: `1e2` is rejected as a field number, an enum number and an integer default, and accepted as a float default. The lexer tested only `.` and `-` until #191, so this reported false for `1e19` and callers needing the spelling had to ask a second predicate.
In base 16 `e` is a digit rather than an exponent marker, so `0x2E` is the integer 46 and only `.` or a `p` exponent makes a hex literal a float.
func (NumberToken) IsLegacyOctal ¶
func (n NumberToken) IsLegacyOctal() bool
IsLegacyOctal returns whether this is a C-style octal literal, such as 0777, as opposed to a modern octal literal like 0o777.
func (NumberToken) IsValid ¶
func (n NumberToken) IsValid() bool
IsValid returns whether this token was able to parse properly at all.
func (NumberToken) Mantissa ¶
func (n NumberToken) Mantissa() source.Span
Mantissa returns the mantissa digits for this literal, i.e., everything between the prefix and the (possibly empty) exponent.
For example, for 0x123.456p-789, this will be 123.456.
func (NumberToken) Prefix ¶
func (n NumberToken) Prefix() source.Span
Prefix returns this number's base prefix (e.g. 0x).
func (NumberToken) Suffix ¶
func (n NumberToken) Suffix() source.Span
Suffix returns an arbitrary suffix attached to this number (the suffix will have no whitespace before the end of the digits).
func (NumberToken) Token ¶
func (n NumberToken) Token() Token
Token returns the wrapped token value.
func (NumberToken) Value ¶
func (n NumberToken) Value() *decimal.Decimal
Value returns the underlying arbitrary-precision numeric value.
type Stream ¶
type Stream struct {
// The file this stream is over.
*source.File
// contains filtered or unexported fields
}
Stream is a token stream.
Internally, Stream uses a compressed representation for storing tokens, and is not precisely a []Token. In particular, it supports the creation of "synthetic" tokens, described in detail in this package's documentation.
Streams may be "frozen", meaning that whatever lexing operation it was meant for is complete, and new tokens cannot be pushed to it. This is used by the Protocompile lexer to prevent re-use of a stream for multiple files.
func (*Stream) All ¶
All returns an iterator over all tokens in this stream. First the natural tokens in order of creation, and then the synthetic tokens in the same.
func (*Stream) Around ¶
Around returns the tokens around the given offset. It has the following potential return values:
func (*Stream) AssertEmpty ¶
func (s *Stream) AssertEmpty()
AssertEmpty asserts that no natural tokens have been created in this stream yet. It panics if they already have.
func (*Stream) Freeze ¶
func (s *Stream) Freeze()
Freeze marks this stream as frozen. This means that all mutation operations except for creation of synthetic tokens will panic.
Freezing cannot be checked for or undone; callers must assume any token stream they did not create has already been frozen.
func (*Stream) FromID ¶
FromID implements id.Context.
func (*Stream) NewFused ¶
NewFused mints a new synthetic open/close pair using the given tokens.
Panics if either open or close is natural or non-leaf.
type StringToken ¶
StringToken provides access to detailed information about a String.
func (StringToken) Escapes ¶
func (s StringToken) Escapes() seq.Indexer[Escape]
Escapes returns the escapes that contribute to the value of this string.
func (StringToken) HasEscapes ¶
func (s StringToken) HasEscapes() bool
HasEscapes returns whether the string had escapes which were processed.
func (StringToken) IsConcatenated ¶
func (s StringToken) IsConcatenated() bool
IsConcatenated returns whether the string was built from implicitly-concatenated strings.
func (StringToken) IsPure ¶
func (s StringToken) IsPure() bool
IsPure returns whether the string required post-processing (escaping or concatenation) after lexing.
func (StringToken) Prefix ¶
func (s StringToken) Prefix() source.Span
Prefix returns an arbitrary prefix attached to this string (the prefix will have no whitespace before the open quote).
func (StringToken) Quotes ¶
func (s StringToken) Quotes() (open, close source.Span)
Quotes returns the opening and closing delimiters for this string literal, not including the sigil.
func (StringToken) RawContent ¶
func (s StringToken) RawContent() source.Span
RawContent returns the unprocessed contents of the string.
func (StringToken) Text ¶
func (s StringToken) Text() string
Text returns the post-processed contents of this string.
func (StringToken) Token ¶
func (s StringToken) Token() Token
Token returns the wrapped token value.
type Token ¶
Token is a lexical element of a Protobuf file.
Protocompile's token stream is actually a tree of tokens. Some tokens, called non-leaf tokens, contain a selection of tokens "within" them. For example, the two matched braces of a message body are a single token, and all of the tokens between the braces are contained inside it. This moves certain complexity into the lexer in a way that allows us to handle matching delimiters generically.
The zero value of Token is the so-called "zero token", which is used to denote the absence of a token.
func (Token) AsNumber ¶
func (t Token) AsNumber() NumberToken
AsNumber returns number information for this token.
func (Token) AsString ¶
func (t Token) AsString() StringToken
AsString returns string information for this token.
func (Token) Children ¶
Children returns a Cursor over the children of this token.
If the token is zero or is a leaf token, returns nil.
func (Token) IsSynthetic ¶
IsSynthetic returns whether this is a non-zero synthetic token (i.e., a token that didn't come from a parsing operation.)
func (Token) Keyword ¶
Keyword returns a keyword.Keyword indicating that this token has special meaning in the grammar.
Both a Keyword and an Ident may produce keyword values; the former are called hard keywords; the latter soft keywords. Soft keywords are meant to be useable as identifiers by a parser unless they happen to be in the right place for their keyword value to matter; hard keywords are rejected when used as identifiers.
func (Token) Kind ¶
Kind returns what kind of token this is.
Returns Unrecognized if this token is zero.
func (Token) LeafSpan ¶
LeafSpan returns the span that this token would have if it was a leaf token.
func (Token) Name ¶
Name converts this token into its corresponding identifier name, potentially performing normalization.
Currently, we perform no normalization, so this is the same value as Text(), but that may change in the future.
Returns "" for non-identifiers.
func (Token) Next ¶
Next returns the next token in this token's stream.
Panics if this is not a natural token.
func (Token) Prev ¶
Prev returns the previous token in this token's stream.
Panics if this is not a natural token.
func (Token) SetKind ¶
SetKind overwrites the kind of this token.
Panics if the token's stream is frozen.
func (Token) StartEnd ¶
StartEnd returns the open and close tokens for this token.
If this is a leaf token, start and end will be the same token and will compare as equal.
Panics if this is a zero token.
func (Token) SyntheticChildren ¶
SyntheticChildren returns a cursor over the given subslice of the children of this token.
Panics if t is not synthetic.
func (Token) Text ¶
Text returns the text fragment referred to by this token. This does not return the text contained inside of non-leaf tokens; if this token refers to a token tree, this will return only the text of the open (or close) token.
For example, for a matched pair of braces, this will only return the text of the open brace, "{".
Returns empty string for the zero token.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package keyword provides Keyword, an enum of all special "grammar particles" (i.e., literal tokens with special meaning in the grammar such as identifier keywords and punctuation) recognized by Protocompile.
|
Package keyword provides Keyword, an enum of all special "grammar particles" (i.e., literal tokens with special meaning in the grammar such as identifier keywords and punctuation) recognized by Protocompile. |