token

package
v0.38.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearMeta

func ClearMeta[M tokenmeta.Meta](token Token)

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

func GetMeta[M tokenmeta.Meta](token Token) *M

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

func MutateMeta[M tokenmeta.Meta](token Token) *M

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

func NewCursorAt(tok Token) *Cursor

NewCursorAt returns a new cursor at the given token.

Panics if the token is zero or synthetic.

func NewSliceCursor

func NewSliceCursor(stream *Stream, slice []ID) *Cursor

NewSliceCursor returns a new cursor over a slice of token IDs in the given context.

func (*Cursor) Clone

func (c *Cursor) Clone() *Cursor

Clone returns a copy of this cursor, which allows performing operations on it without mutating the original cursor.

func (*Cursor) Context

func (c *Cursor) Context() *Stream

Context returns this Cursor's context.

func (*Cursor) Done

func (c *Cursor) Done() bool

Done returns whether or not there are still tokens left to yield.

func (*Cursor) IsSynthetic

func (c *Cursor) IsSynthetic() bool

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

func (c *Cursor) NewLinesBetween(a, b Token, limit int) int

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) Next

func (c *Cursor) Next() Token

Next returns the next token in the sequence, and advances the cursor.

func (*Cursor) NextSkippable

func (c *Cursor) NextSkippable() Token

NextSkippable returns the next skippable token in the sequence, and advances the cursor.

func (*Cursor) Peek

func (c *Cursor) Peek() Token

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

func (c *Cursor) PeekPrev() Token

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

func (c *Cursor) PeekPrevSkippable() Token

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

func (c *Cursor) PeekSkippable() Token

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) Prev

func (c *Cursor) Prev() Token

Prev returns the previous token in the sequence, and decrements the cursor.

func (*Cursor) PrevSkippable

func (c *Cursor) PrevSkippable() Token

PrevSkippable returns the previous skippable token in the sequence, and decrements the cursor.

func (*Cursor) Rest

func (c *Cursor) Rest() iter.Seq[Token]

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

func (c *Cursor) RestSkippable() iter.Seq[Token]

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.

func (*Cursor) SeekToEnd

func (c *Cursor) SeekToEnd() (Token, source.Span)

SeekToEnd returns a span for whatever comes immediately after the end of this cursor (be that a token or the EOF), and advances the cursor to the end. If it is a token, this will return that token, too.

Returns Zero for a synthetic cursor.

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

type ID = id.ID[Token]

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) GoString

func (v Kind) GoString() string

GoString implements fmt.GoStringer.

func (Kind) IsSkippable

func (t Kind) IsSkippable() bool

IsSkippable returns whether this is a token that should be examined during syntactic analysis.

func (Kind) String

func (v Kind) String() string

String implements fmt.Stringer.

type NumberToken

type NumberToken id.Node[NumberToken, *Stream, *tokenmeta.Number]

NumberToken provides access to detailed information about a Number.

func (NumberToken) Base

func (n NumberToken) Base() byte

Base returns this number's base.

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

func (s *Stream) All() iter.Seq[Token]

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

func (s *Stream) Around(offset int) (Token, Token)

Around returns the tokens around the given offset. It has the following potential return values:

  1. offset == 0, returns Zero, first token.
  2. offset == len(File.Text()), returns last token, Zero.
  3. offset is the end of a token. Returns the tokens ending and starting at offset, respectively.
  4. offset is inside of a token tok. Returns tok, tok.

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) Cursor

func (s *Stream) Cursor() *Cursor

Cursor returns a cursor over the natural token stream.

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

func (s *Stream) FromID(id uint64, want any) any

FromID implements id.Context.

func (*Stream) NewFused

func (s *Stream) NewFused(openTok, closeTok Token, children ...Token)

NewFused mints a new synthetic open/close pair using the given tokens.

Panics if either open or close is natural or non-leaf.

func (*Stream) NewIdent

func (s *Stream) NewIdent(name string) Token

NewIdent mints a new synthetic identifier token with the given name.

func (*Stream) NewPunct

func (s *Stream) NewPunct(text string) Token

NewPunct mints a new synthetic punctuation token with the given text.

func (*Stream) NewString

func (s *Stream) NewString(text string) Token

NewString mints a new synthetic string containing the given text.

func (*Stream) Push

func (s *Stream) Push(length int, kind Kind) Token

Push mints the next token referring to a piece of the input source.

Panics if this stream is frozen.

func (*Stream) PushKeyword

func (s *Stream) PushKeyword(length int, kind Kind, kw keyword.Keyword) Token

Push mints the next token referring to a piece of the input source, marking it with the given keyword.

Panics if this stream is frozen.

type StringToken

type StringToken id.Node[StringToken, *Stream, *tokenmeta.String]

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

type Token id.Node[Token, *Stream, rawToken]

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.

var Zero Token

Zero is the zero 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

func (t Token) Children() *Cursor

Children returns a Cursor over the children of this token.

If the token is zero or is a leaf token, returns nil.

func (Token) IsLeaf

func (t Token) IsLeaf() bool

IsLeaf returns whether this is a non-zero leaf token.

func (Token) IsSynthetic

func (t Token) IsSynthetic() bool

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

func (t Token) Keyword() keyword.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

func (t Token) Kind() Kind

Kind returns what kind of token this is.

Returns Unrecognized if this token is zero.

func (Token) LeafSpan

func (t Token) LeafSpan() source.Span

LeafSpan returns the span that this token would have if it was a leaf token.

func (Token) Name

func (t Token) Name() string

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

func (t Token) Next() Token

Next returns the next token in this token's stream.

Panics if this is not a natural token.

func (Token) Prev

func (t Token) Prev() Token

Prev returns the previous token in this token's stream.

Panics if this is not a natural token.

func (Token) SetKind

func (t Token) SetKind(k Kind)

SetKind overwrites the kind of this token.

Panics if the token's stream is frozen.

func (Token) Span

func (t Token) Span() source.Span

Span implements [Spanner].

func (Token) StartEnd

func (t Token) StartEnd() (start, end Token)

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) String

func (t Token) String() string

String implements strings.Stringer.

func (Token) SyntheticChildren

func (t Token) SyntheticChildren(i, j int) *Cursor

SyntheticChildren returns a cursor over the given subslice of the children of this token.

Panics if t is not synthetic.

func (Token) Text

func (t Token) Text() string

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.

type Value

type Value interface {
	uint64 | float64 | *big.Int | string
}

Value is a constraint that represents a literal scalar value in source.

This union does not include bool because they are lexed as identifiers and then later converted to boolean values based on their context (since "true" and "false" are also valid identifiers for named types).

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.

Jump to

Keyboard shortcuts

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