Documentation
¶
Index ¶
- Variables
- func PrettyWrite(out io.Writer, r any) error
- func SimpleTokeniser(tokenDefs []TokenDef) func(string) (*SimpleTokenStream, error)
- type Empty
- type FieldType
- type FirstSet
- type Match
- type Memoisable
- type OneOf
- type OneOf2
- type OneOf3
- type OneOf4
- type OneOf5
- type OneOf6
- type OneOfValue
- type ParseError
- func EmptyMatchError(s *ParserState, ruleName string) *ParseError
- func Parse(dest any, s TokenStream, opts ...ParseOption) *ParseError
- func ParseOptional[T any](s *ParserState, tokOpts TokenOptions, first FirstSet) (*T, *ParseError)
- func ParseRepeated[T any](s *ParserState, tokOpts TokenOptions, opts RepeatOptions) (items []T, n int, err *ParseError, ok bool)
- func ParseWithOptions(dest any, s *ParserState, opts TokenOptions) *ParseError
- type ParseOption
- type Parser
- type ParserState
- type Position
- type PrettyWriter
- type RepeatOptions
- type RuleDef
- type RuleField
- type Seq
- type SimpleToken
- type SimpleTokenStream
- type SizeOptions
- type Tok
- type Token
- type TokenDef
- type TokenOptions
- type TokenParseOptions
- type TokenStream
- type TrailMode
Constants ¶
This section is empty.
Variables ¶
var EOF = SimpleToken{
TokType: "EOF",
TokValue: "EOF",
}
EOF is the token that is returned when trying to consument an exhausted token stream.
var ErrNotExhausted = errors.New("expected end of input")
ErrNotExhausted is the Err of the *ParseError returned by Parse with the Exhaust option when some input is left after the rule matched.
var WithDefaultLogger = WithLogger(log.Default())
Functions ¶
func SimpleTokeniser ¶
func SimpleTokeniser(tokenDefs []TokenDef) func(string) (*SimpleTokenStream, error)
SimpleTokeniser takes a list of TokenDefs and returns a function that tokenises a string, returning a stream whose tokens are of type *SimpleToken. It panics if a definition is invalid (bad pattern, unknown PushMode, ...).
At each point in the input the definition with the longest match wins, and among those matching the same length the first one listed, as with lex. So keywords can be listed before an identifier pattern that also matches them without clashing with longer identifiers that start with a keyword. A match of length 0 does not count, and if no definition matches, an error is returned.
Types ¶
type Empty ¶
type Empty struct{}
func (Empty) Parse ¶
func (Empty) Parse(r interface{}, s *ParserState, opts TokenOptions) *ParseError
type FirstSet ¶ added in v0.2.0
type FirstSet struct {
// contains filtered or unexported fields
}
A FirstSet describes the tokens a rule can start with. A OneOf uses the first sets of its alternatives to skip, without allocating or parsing them, those that cannot start with the next token; Seq does the same with its optional and repeated fields.
First sets are computed from the rule definitions (struct tags). A rule that may match without consuming a token, or a custom rule (one with its own Parse method that is not a OneOfN), is never skipped.
func FirstSetOf ¶ added in v0.2.0
func FirstSetOf[T any](tokOpts TokenOptions) FirstSet
FirstSetOf returns the first set of a field of type T parsed with the given token options (see FirstSet).
type Match ¶
type Match struct{}
func (Match) Parse ¶
func (Match) Parse(r interface{}, s *ParserState, opts TokenOptions) *ParseError
type Memoisable ¶ added in v0.2.0
type Memoisable interface {
MemoKey(opts TokenOptions) any
}
A Memoisable rule has the result of its Parse method cached by stream position (packrat parsing), which also makes left recursion through it work. For the cache to be valid, the outcome of Parse must be fully determined by the rule type, the stream position and the key returned by MemoKey; a rule for which that is not true must not implement Memoisable and is then parsed afresh every time.
Seq, OneOf and the OneOfN types implement it, returning a nil key, as they ignore the token options passed to Parse; a struct rule embedding one of them inherits the method, so if it overrides Parse the override must obey the same rule. A custom rule whose result depends on the token options should return opts.Key().
Note that only memoised rules can be the head of a left-recursive cycle.
type OneOf ¶
type OneOf struct{}
OneOf should be used as the first field of a Rule struct to signify that it should match exactly one of the fields
func (OneOf) MemoKey ¶ added in v0.2.0
func (OneOf) MemoKey(opts TokenOptions) any
MemoKey implements Memoisable: a OneOf rule ignores the token options.
func (OneOf) Parse ¶
func (OneOf) Parse(r interface{}, s *ParserState, opts TokenOptions) *ParseError
type OneOf2 ¶ added in v0.2.0
type OneOf2[T1, T2 any] struct { OneOfValue }
OneOf2 is a rule that matches the first of T1, T2 that parses, in that order. Each type parameter must be a rule type, i.e. a pointer to it must implement Parser; this is checked when the rule is first parsed, not at compile time, because Go cannot express "pointer to T implements Parser" without doubling the type parameters.
OneOf3 to OneOf6 are the same for more alternatives.
The recommended way to use these types is to embed them in a named struct rather than to define a type alias, so that methods can be defined on the rule and so that it has a short name in errors and debug output:
type Value struct {
grammar.OneOf3[Number, String, List]
}
func (v *Value) Compile() any {
switch x := v.Value.(type) {
case *Number: ...
case *String: ...
case *List: ...
}
}
func (*OneOf2[T1, T2]) Parse ¶ added in v0.2.0
func (o *OneOf2[T1, T2]) Parse(r any, s *ParserState, opts TokenOptions) *ParseError
type OneOf3 ¶ added in v0.2.0
type OneOf3[T1, T2, T3 any] struct { OneOfValue }
func (*OneOf3[T1, T2, T3]) Parse ¶ added in v0.2.0
func (o *OneOf3[T1, T2, T3]) Parse(r any, s *ParserState, opts TokenOptions) *ParseError
type OneOf4 ¶ added in v0.2.0
type OneOf4[T1, T2, T3, T4 any] struct { OneOfValue }
func (*OneOf4[T1, T2, T3, T4]) Parse ¶ added in v0.2.0
func (o *OneOf4[T1, T2, T3, T4]) Parse(r any, s *ParserState, opts TokenOptions) *ParseError
type OneOf5 ¶ added in v0.2.0
type OneOf5[T1, T2, T3, T4, T5 any] struct { OneOfValue }
func (*OneOf5[T1, T2, T3, T4, T5]) Parse ¶ added in v0.2.0
func (o *OneOf5[T1, T2, T3, T4, T5]) Parse(r any, s *ParserState, opts TokenOptions) *ParseError
type OneOf6 ¶ added in v0.2.0
type OneOf6[T1, T2, T3, T4, T5, T6 any] struct { OneOfValue }
func (*OneOf6[T1, T2, T3, T4, T5, T6]) Parse ¶ added in v0.2.0
func (o *OneOf6[T1, T2, T3, T4, T5, T6]) Parse(r any, s *ParserState, opts TokenOptions) *ParseError
type OneOfValue ¶ added in v0.2.0
type OneOfValue struct {
Value any
}
OneOfValue holds the result of parsing one of the generic OneOfN rules. Value is a pointer to the alternative that matched (e.g. *T2 for the second type parameter of OneOf3[T1, T2, T3]), so it is usually consumed with a type switch.
func (OneOfValue) MemoKey ¶ added in v0.2.0
func (OneOfValue) MemoKey(opts TokenOptions) any
MemoKey implements Memoisable: the OneOfN rules ignore the token options.
func (*OneOfValue) PrettyWrite ¶ added in v0.2.0
type ParseError ¶
type ParseError struct {
Err error
Token
TokenParseOptions []TokenParseOptions
Pos int
}
A ParseError describes where a parse failed: the position and token, the tokens that were expected there (TokenParseOptions, from "tok" tags) and any other reason (Err). Parse returns the furthest failure of the parse, which is where the input went wrong.
During a parse, the *ParseError returned by a failing rule is shared by all failures and describes the furthest one so far, not necessarily the rule's own failure (see ParserState.Fail).
func EmptyMatchError ¶ added in v0.2.0
func EmptyMatchError(s *ParserState, ruleName string) *ParseError
EmptyMatchError is the error a generated Seq rule returns when none of its fields matched anything.
func Parse ¶
func Parse(dest any, s TokenStream, opts ...ParseOption) *ParseError
Parse tries to interpret dest as a grammar rule and use it to parse the given token stream. Parse can panic if dest is not a valid grammar rule. It returns a non-nil *ParseError if the token stream does not match the rule.
func ParseOptional ¶ added in v0.2.0
func ParseOptional[T any](s *ParserState, tokOpts TokenOptions, first FirstSet) (*T, *ParseError)
ParseOptional parses an optional (pointer) field of type T, unless its first set says it cannot start with the next token. On failure it returns nil and the error, with the stream restored to where it was.
func ParseRepeated ¶ added in v0.2.0
func ParseRepeated[T any](s *ParserState, tokOpts TokenOptions, opts RepeatOptions) (items []T, n int, err *ParseError, ok bool)
ParseRepeated parses a repeated field of items of type T with the given token and repeat options. See repeatCore for the meaning of the results.
func ParseWithOptions ¶
func ParseWithOptions(dest any, s *ParserState, opts TokenOptions) *ParseError
ParseWithOptions is the same as Parse but the ParseOptions are explicitely given (this is mostly used by the parser generator).
func (*ParseError) Error ¶
func (e *ParseError) Error() string
func (*ParseError) Merge ¶
func (e *ParseError) Merge(e2 *ParseError) *ParseError
Merge returns the error describing the furthest of the two failures, or both if they are at the same position. Errors returned by the rules of this package are all the shared record of the furthest failure (see ParserState.Fail), so merging them is a no-op; a custom rule combining errors it allocated itself may need it.
type ParseOption ¶
type ParseOption func(s *ParserState)
var Exhaust ParseOption = func(s *ParserState) { s.exhaust = true }
Exhaust makes Parse fail unless the whole token stream is consumed. Without it, Parse succeeds as soon as the rule matches a prefix of the input, so e.g. an expression grammar happily parses `1 +` as `1`. With it, leftover input yields a *ParseError whose Err is ErrNotExhausted, unless the parser got further while trying to match more, in which case that (usually more helpful) error is returned instead.
func WithLogger ¶
func WithLogger(l *log.Logger) ParseOption
type Parser ¶
type Parser interface {
Parse(r any, s *ParserState, opts TokenOptions) *ParseError
}
A Parser can parse a token stream to populate itself. It must return an error if it fails to do it.
A Parser that also implements Memoisable has its results cached (see Memoisable); one that does not is parsed afresh every time.
type ParserState ¶
type ParserState struct {
TokenStream
// contains filtered or unexported fields
}
func (*ParserState) Debug ¶
func (s *ParserState) Debug() bool
func (*ParserState) Fail ¶ added in v0.2.0
func (s *ParserState) Fail(pos int, tok Token, err error) *ParseError
Fail records that parsing failed at stream position pos, on token tok, for the given reason, and returns the error for the Parse method to return. A custom rule uses it to report a failure other than a token mismatch (which TokenOptions.MatchNextToken records itself):
pos := s.Save()
tok, err := opts.MatchNextToken(s)
if err != nil {
return err
}
if !valid(tok) {
return s.Fail(pos, tok, errors.New("invalid literal"))
}
Only the furthest failure of a parse is recorded (with every reason given for it), as it is where the input actually went wrong; earlier ones are dropped. The *ParseError returned is the same for all failures of a parse and describes the furthest one, so a rule should not expect it to describe its own failure; it only means "failed".
func (*ParserState) Logf ¶
func (s *ParserState) Logf(fstr string, args ...any)
func (*ParserState) Peek ¶ added in v0.2.0
func (s *ParserState) Peek() Token
Peek returns the next token without consuming it.
type PrettyWriter ¶ added in v0.2.0
type RepeatOptions ¶ added in v0.2.0
type RepeatOptions struct {
SizeOptions
Sep TokenOptions
Trail TrailMode
Drop TokenOptions // tokens to skip before each item and separator
First FirstSet // of an item
}
RepeatOptions gathers the options of a repeated field, the drop options of its rule and the first set of its items.
func MustRepeatOptions ¶ added in v0.2.0
func MustRepeatOptions[T any](size, sep, trail, drop, tok string) RepeatOptions
MustRepeatOptions is RepeatOptionsFromTags for package-level variables in generated code; it panics on an invalid tag.
func RepeatOptionsFromTags ¶ added in v0.2.0
func RepeatOptionsFromTags[T any](size, sep, trail, drop, tok string) (RepeatOptions, error)
RepeatOptionsFromTags parses the "size", "sep", "trail" and "tok" struct tags of a repeated field of items of type T and the "drop" tag of its rule.
type RuleDef ¶
type RuleDef struct {
Name string
OneOf bool
DropOptions TokenOptions
Fields []RuleField
// contains filtered or unexported fields
}
type RuleField ¶
type RuleField struct {
FieldType
TokenOptions
SizeOptions
SepOptions TokenOptions
Trail TrailMode
Name string
Index int
}
func (RuleField) RepeatOptions ¶ added in v0.2.0
func (f RuleField) RepeatOptions(drop TokenOptions, first FirstSet) RepeatOptions
RepeatOptions returns the repeat options of the field, with the given drop options and item first set.
type Seq ¶
type Seq struct{}
Seq should be used as the first field of a Rule struct to signify that it should match all the fields in sequence.
func (Seq) MemoKey ¶ added in v0.2.0
func (Seq) MemoKey(opts TokenOptions) any
MemoKey implements Memoisable: a Seq rule ignores the token options.
func (Seq) Parse ¶
func (Seq) Parse(r interface{}, s *ParserState, opts TokenOptions) *ParseError
type SimpleToken ¶
SimpleToken is a simple implementation of the both the Token and the Parser interfaces. So it can be used in rules to match a token field. It is also the concrete type of Tokens returned by SimpleTokenStream.
func (*SimpleToken) Parse ¶
func (t *SimpleToken) Parse(_ interface{}, s *ParserState, opts TokenOptions) *ParseError
Parse tries to match the next token in the given TokenStream with the ParseOptions, using opts.MatchToken. If they match, the receiver is loaded with the token data, if not a non-nil *ParseError is returned. In any event the next token in the token stream has been consumed.
func (SimpleToken) Position ¶ added in v0.2.0
func (t SimpleToken) Position() Position
func (SimpleToken) PrettyWrite ¶ added in v0.2.0
func (SimpleToken) Value ¶
func (t SimpleToken) Value() string
Value returns the value of the token.
type SimpleTokenStream ¶
type SimpleTokenStream struct {
// contains filtered or unexported fields
}
SimpleTokenStream is a very simple implementation of the TokenStream interface which the Parse function requires.
func NewSimpleTokenStream ¶
func NewSimpleTokenStream(toks []Token) *SimpleTokenStream
NewSimpleTokenStream makes a token stream from a slice of tokens. The EOF token it returns at the end is positioned just after the last token.
func (*SimpleTokenStream) Dump ¶
func (s *SimpleTokenStream) Dump(w io.Writer)
func (*SimpleTokenStream) Next ¶
func (s *SimpleTokenStream) Next() Token
Next consumes the next token in the token stream and returns it. If the stream is exhausted, EOF is returned.
func (*SimpleTokenStream) Restore ¶
func (s *SimpleTokenStream) Restore(pos int)
Restore rewinds the token stream to the given position (which should have been obtained by s.Save()). In general this may panic - in this implementation it's always possible to rewind.
func (*SimpleTokenStream) Save ¶
func (s *SimpleTokenStream) Save() int
Save returns the current position in the token stream.
type SizeOptions ¶
type SizeOptions struct {
Min, Max int
}
func SizeOptionsFromTag ¶ added in v0.2.0
func SizeOptionsFromTag(tag string) (SizeOptions, error)
SizeOptionsFromTag parses the value of a "size" struct tag.
type Tok ¶ added in v0.2.0
type Tok struct {
SimpleToken
}
func (*Tok) Parse ¶ added in v0.2.0
func (t *Tok) Parse(r any, s *ParserState, opts TokenOptions) *ParseError
type Token ¶
type Token interface {
Type() string // The type of the token (e.g. operator, number, string, identifier)
Value() string // The value of the token(e.g. `+`, `123`, `"abc"`, `if`)
Position() Position // The position of the token in the source text
}
A Token has a Type() and Value() method. A TokenStream's Next() method must return a Token.
type TokenDef ¶
type TokenDef struct {
Ptn string // Regular expression matching the token
Name string // Token type; empty means the token is skipped
Scan func(string) int // Length of the token at the start of the input (0: no match)
Mode string // Mode the definition belongs to
PushMode string // Mode to enter after this token
PopMode bool // Return to the previous mode after this token
}
A TokenDef defines a type of token and how to recognise it. A list of them makes a tokeniser with SimpleTokeniser.
A token is recognised by its pattern (Ptn), a regular expression matched at the start of the remaining input, or by a Scan function, or both: when both are given the pattern must match first and Scan then decides the length of the token. Scan is given the remaining input and returns the length of the token at its start, or 0 if there is none, which lets it recognise what a regular expression cannot, like nested comments.
Modes allow different sets of tokens in different contexts (e.g. inside a string template). A definition belongs to the mode named by Mode; the initial mode is that of the first definition. Matching a token with a PushMode enters that mode, matching one with PopMode returns to the previous one. As an empty PushMode means no push, a mode that is pushed needs a name, so if the initial mode is, give it one.
type TokenOptions ¶
type TokenOptions struct {
TokenParseOptions []TokenParseOptions
}
func TokenOptionsFromTag ¶ added in v0.2.0
func TokenOptionsFromTag(tag string) TokenOptions
TokenOptionsFromTag parses the value of a "tok", "sep" or "drop" struct tag.
func (TokenOptions) DropMatchingNextTokens ¶
func (o TokenOptions) DropMatchingNextTokens(s TokenStream)
func (TokenOptions) Key ¶ added in v0.2.0
func (o TokenOptions) Key() any
Key returns a comparable value identifying the options, for use by Memoisable rules whose Parse result depends on them.
func (TokenOptions) MatchNextToken ¶
func (o TokenOptions) MatchNextToken(s *ParserState) (Token, *ParseError)
MatchNextToken consumes the next token of the stream if it matches one of the options and returns it. If it does not, the failure is recorded (see ParserState.Fail) and the error returned with the token.
type TokenParseOptions ¶
func (TokenParseOptions) String ¶
func (o TokenParseOptions) String() string
type TokenStream ¶
type TokenStream interface {
Next() Token // Advance the stream by one token and return it.
Save() int // Return the current position in the token stream.
Restore(int) // Return the stream to the given position.
}
A TokenStream represents a sequence of tokens that will be consumed by the Parse() function. The SimpleTokenStream implementation in this package can be used, or users can provide their own implementation (e.g. with a richer data type for tokens, or "on demand" tokenisation).
The Restore() method may panic if is not possible to return to the given position.
type TrailMode ¶ added in v0.2.0
type TrailMode int
TrailMode says what a repeated field with a separator does about a separator after the last item. It is set with the "trail" struct tag.
const ( // TrailNone (the default): items are separated, a trailing separator is // not part of the field, e.g. `1, 2`. TrailNone TrailMode = iota // TrailOptional: a trailing separator is accepted but not required, e.g. // `1, 2` or `1, 2,`. TrailOptional // TrailRequired: every item, including the last, must be followed by the // separator (it acts as a terminator), e.g. `1; 2;`. TrailRequired )
func TrailModeFromTag ¶ added in v0.2.0
TrailModeFromTag parses the value of a "trail" struct tag.