grammar

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 13 Imported by: 3 modules, 1 package

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.

README

grammar

CI

A parser library for Go where the rules are Go structs and the parse tree is those same structs, filled in. There is no separate grammar file or DSL: the type you want to get out of the parser is the grammar. Parsing uses reflection by default; a generator can produce equivalent reflection-free code if you want it.

The parser is a memoising ("packrat") recursive descent parser with PEG semantics: ordered choice, greedy repetition, and left recursion supported.

The concepts are introduced in the example below. There are more examples in examples/: json is the most complete, sjson shows the generic one-of types and expr shows a left-recursive expression grammar.

Rules

Rules are Go structs whose first field says what kind of rule it is. Here is a definition for s-expressions:

import "github.com/arnodel/grammar"

type Token = grammar.SimpleToken

// SExpr ::= Number | String | Atom | List
type SExpr struct {
    grammar.OneOf                // A "one-of" rule: exactly one of the fields below matches
    Number *Token `tok:"number"` // A pointer field is an alternative; this one matches a "number" token
    String *Token `tok:"string"`
    Atom   *Token `tok:"atom"`
    *List                        // An embedded pointer works too, the field is named List
}

// List ::= "(" SExpr* ")"
type List struct {
    grammar.Seq                           // A sequence rule: all fields match in order
    OpenBkt  grammar.Match `tok:"bkt,("`  // Matches a "bkt" token with value "(" (and stores nothing)
    Items    []SExpr                      // A slice field matches zero or more items
    CloseBkt grammar.Match `tok:"bkt,)"`
}

There are three kinds of rule, chosen by the first (embedded) field:

  • grammar.Seq: every field must match, in order.
  • grammar.OneOf: the first field that matches wins (ordered choice). All fields must be pointers or slices.
  • grammar.Tok: the rule matches a single token; the struct has no other field and the tok tag goes on the grammar.Tok field itself. See Tokens below.

Within a rule, the type of a field says how it matches:

  • A plain field (Items SExpr) must match.
  • A pointer field (Number *Token) is optional in a Seq, and one alternative in a OneOf.
  • A slice field (Items []SExpr) matches a run of items. In a OneOf, the alternative matches if there is at least one item.

Field types can be other rule types, grammar.Match, your token type, or anything implementing grammar.Parser. grammar.Match is an empty struct: it matches the token given by its tok tag and takes no space in the result. grammar.Empty always matches and consumes nothing.

Tags
tag on meaning
tok:"type" a token field match a token of this type
tok:"type,value" a token field match a token of this type with this value
tok:"a|b,x" a token field alternatives, separated by |
tok:"type*" a token field a * after the type matches without consuming the token (lookahead)
sep:"type,value" a slice field items are separated by this token
trail:"optional" a slice field with sep a separator after the last item is allowed (1, 2,)
trail:"required" a slice field with sep every item must be followed by the separator (1; 2;)
size:"n", size:"min-max", size:"min-", size:"-max" a slice field bounds on the number of items
drop:"type" the Seq or OneOf field tokens of this type are skipped before each field, item and separator of the rule (e.g. whitespace or comments that the tokeniser keeps)

A slice with no size matches zero or more items. A separator is matched only between items unless a trail mode says otherwise.

Generic one-of rules

For a rule that is purely a choice between other rules, the generic types grammar.OneOf2 to grammar.OneOf6 avoid the wrapper struct. Embed one in a named struct (a type alias would not let you define methods on it):

type Number struct {
    grammar.Tok `tok:"number"`
}

type SJSON struct {
    grammar.OneOf5[Number, String, Boolean, List, Object]
}

After parsing, Value holds a pointer to the alternative that matched, so it is consumed with a type switch:

switch v := sjson.Value.(type) {
case *Number:
    ...
case *List:
    ...
}

The type parameters are unconstrained (any) because Go cannot express "pointer to T implements Parser" without doubling them; an argument that is not a rule type is reported when the rule is first parsed.

Tokens

The parser consumes a grammar.TokenStream, whose tokens implement grammar.Token: a type, a value and a position. You can write your own token and stream types, or use grammar.SimpleToken and build a tokeniser with grammar.SimpleTokeniser:

var tokenise = grammar.SimpleTokeniser([]grammar.TokenDef{
    {
        // If Name is empty, the token is skipped in the token stream
        Ptn: `\s+`, // A regular expression, matched at the start of the input
    },
    {
        Name: "bkt", // The token type, as seen in "tok" struct tags
        Ptn:  `[()]`,
    },
    {
        Name: "string",
        Ptn:  `"[^"]*"`,
    },
    {
        Name: "number",
        Ptn:  `-?[0-9]+(?:\.[0-9]+)?`,
    },
    {
        Name: "atom",
        Ptn:  `[a-zA-Z_][a-zA-Z0-9_-]*`,
    },
})

At each point in the input the definition with the longest match wins, and among equal matches the first one listed, so keywords can be listed before an identifier pattern without clashing with longer identifiers. Literal patterns and character classes are matched without running a regular expression.

A Scan func(string) int on a definition takes over from the pattern (or complements it: when both are given the pattern decides whether Scan is tried, and Scan decides the length of the token). It returns the length of the token at the start of the remaining input, or 0, and covers what a regular expression cannot, like nested comments or strings with escapes:

    {
        Name: "comment",
        Ptn:  `/\*`,
        Scan: scanNestedComment, // func(string) int
    },

Definitions can be grouped into modes (Mode), entered and left with PushMode and PopMode on the tokens that switch context, e.g. for string interpolation.

grammar.SimpleToken is also a Parser, so a field of that type matches a token and stores it. grammar.Tok wraps it for use as the first field of a single-token rule type, which is handy with the generic one-of types.

Parsing

tokenStream, _ := tokenise(`(cons a (list 123 "c"))`)
var sexpr SExpr
err := grammar.Parse(&sexpr, tokenStream, grammar.Exhaust)

sexpr is now filled in: sexpr.List.Items is a slice of SExpr, and sexpr.List.Items[0].Atom is a Token of type atom with value cons.

grammar.Exhaust makes the parse fail unless all the input was consumed; without it a rule may match just a prefix. The error is a *grammar.ParseError with the offending token, its position and what was expected there:

Ln 1, Col 7: number with value "3": expected token with value "+"; expected end of input

grammar.WithLogger(logger) traces the parse, which helps when a grammar does not do what you expect.

To look at a parse tree, grammar.PrettyWrite writes a readable form of it:

grammar.PrettyWrite(os.Stdout, &sexpr)
SExpr {
  List: List {
    Items: [
      SExpr {
        Atom: atom = "cons" Ln 1, Col 2
      }
      SExpr {
        Atom: atom = "a" Ln 1, Col 7
      }
      SExpr {
        List: List {
          Items: [
            SExpr {
              Atom: atom = "list" Ln 1, Col 10
            }
            SExpr {
              Number: number = "123" Ln 1, Col 15
            }
            SExpr {
              String: string = "\"c\"" Ln 1, Col 19
            }
          ]
        }
      }
    ]
  }
}

Empty optional fields, empty slices and Match fields are omitted.

Semantics

The parser works like a PEG parser, which differs from a context-free grammar in two ways that matter when you write rules:

  • Choice is ordered. A OneOf takes the first alternative that matches, not the longest. Put the more specific alternative first.
  • Repetition is greedy and does not backtrack. A slice field takes as many items as it can; if what follows then fails to match, the parser does not try again with fewer items.

Results are memoised by rule type and position, so parsing is linear in the size of the input for grammars whose alternatives share prefixes, and the same sub-rule is never parsed twice at the same place.

A OneOf does not try an alternative that cannot start with the next token, nor does a Seq try an optional field or a repeated item that cannot: the tokens a rule can start with (its first set) are computed from the struct tags. This changes nothing to what is parsed or to error messages, it only saves work.

Left recursion

Thanks to memoisation, rules may be left recursive, which is the natural way to write left-associative operators:

// Expr ::= Expr "+" Num | Num
type Expr struct {
    grammar.OneOf
    Sum *Sum
    Num *Num
}

type Sum struct {
    grammar.Seq
    Lhs  Expr
    Plus grammar.Match `tok:"op,+"`
    Rhs  Num
}

type Num struct {
    grammar.Tok `tok:"number"`
}

Parsing 1 + 2 + 3 gives Sum{Sum{1, 2}, 3}. Indirect left recursion (through several rules) works too.

Custom rules

Any type with a Parse(r any, s *grammar.ParserState, opts grammar.TokenOptions) *grammar.ParseError method is a rule. opts holds the tok tag of the field being parsed. If the result of Parse depends only on the rule type, the position and the options, the type can also implement grammar.Memoisable to have its results cached:

func (w *Word) MemoKey(opts grammar.TokenOptions) any {
    return opts.Key()
}

Rules that do not implement it are parsed afresh every time, which is the right default for cheap token-like rules.

A rule reports a token mismatch by returning the error from opts.MatchNextToken(s), and any other failure with s.Fail; s.Peek() returns the next token without consuming it:

func (n *EvenNumber) Parse(r any, s *grammar.ParserState, opts grammar.TokenOptions) *grammar.ParseError {
    pos := s.Save()
    tok, err := opts.MatchNextToken(s)
    if err != nil {
        return err
    }
    if !isEven(tok.Value()) {
        return s.Fail(pos, tok, errors.New("odd number"))
    }
    n.Value = tok.Value()
    return nil
}

The parser state keeps a record of the furthest failure so far, with every reason given for it, and that is what grammar.Parse reports: the furthest point reached is where the input went wrong. Both functions above record into it and return a pointer to it, so no error is allocated while parsing, and the error a rule gets back from a sub-rule only means "failed"; it does not necessarily describe that sub-rule's own failure.

The first set of a custom rule is unknown, so it is always tried (see Semantics). Putting a Match on a keyword or other token before a custom rule in a Seq lets the sequence as a whole be skipped.

Generating a parser

The above works using reflection. It is also possible to generate, for each rule type, a Parse method that does the same thing without reflection. The generated methods call back into the grammar package for the logic of repeated fields, errors and tags, so they behave exactly like the reflection based ones; they are about twice as fast on the JSON example and allocate half as much.

Add this line to the file containing the grammar you want to compile:

//go:generate go run github.com/arnodel/grammar/cmd/genparse

Then run go generate in your package. If your file is called say grammar.go, this generates a file in the same package called grammar.compiled.go, with a Parse method for every struct type whose first field is grammar.Seq, grammar.OneOf or grammar.Tok. You parse files the same way as before with grammar.Parse(), which now runs the generated code. The generic OneOfN types need nothing generated as they never used reflection.

The generated file has the build constraint !nocompiledgrammar, so you can always go back to reflection by building with -tags nocompiledgrammar. This is also a convenient way to check that the two agree: run your tests with and without the tag.

The generator only looks at one file, so a rule whose fields refer to rule types in other files of the package is fine, but each file holding rule types needs its own go:generate line.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var EOF = SimpleToken{
	TokType:  "EOF",
	TokValue: "EOF",
}

EOF is the token that is returned when trying to consument an exhausted token stream.

View Source
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.

View Source
var WithDefaultLogger = WithLogger(log.Default())

Functions

func PrettyWrite

func PrettyWrite(out io.Writer, r any) error

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

func (Empty) PrettyWrite added in v0.2.0

func (Empty) PrettyWrite(out io.Writer, r any, pfx string, indent int) (err error)

type FieldType

type FieldType struct {
	BaseType reflect.Type
	Pointer  bool
	Array    bool
}

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

func (FirstSet) Accepts added in v0.2.0

func (f FirstSet) Accepts(tok Token) bool

Accepts reports whether a rule with this first set may start with tok.

type Match

type Match struct{}

func (Match) Parse

func (Match) Parse(r interface{}, s *ParserState, opts TokenOptions) *ParseError

func (Match) PrettyWrite added in v0.2.0

func (Match) PrettyWrite(out io.Writer, r any, pfx string, indent int) (err error)

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

func (o *OneOfValue) PrettyWrite(out io.Writer, r any, pfx string, indent int) (err error)

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 Position added in v0.2.0

type Position struct {
	Line, Column int
}

func (*Position) Advance added in v0.2.0

func (p *Position) Advance(s string)

func (Position) String added in v0.2.0

func (p Position) String() string

type PrettyWriter added in v0.2.0

type PrettyWriter interface {
	PrettyWrite(out io.Writer, r any, pfx string, indent int) (err error)
}

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

type SimpleToken struct {
	TokType  string
	TokValue string
	TokPos   Position
}

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 (t SimpleToken) PrettyWrite(out io.Writer, r any, pfx string, indent int) (err error)

func (SimpleToken) Type

func (t SimpleToken) Type() string

Type returns the token type.

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

func (*Tok) PrettyWrite added in v0.2.0

func (t *Tok) PrettyWrite(out io.Writer, r any, pfx string, indent int) error

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

type TokenParseOptions struct {
	TokenType    string
	TokenValue   string
	DoNotConsume bool
}

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

func TrailModeFromTag(tag string) (TrailMode, error)

TrailModeFromTag parses the value of a "trail" struct tag.

Directories

Path Synopsis
cmd
genparse command
Command genparse generates reflection-free Parse methods for the grammar rules defined in a Go source file.
Command genparse generates reflection-free Parse methods for the grammar rules defined in a Go source file.
examples

Jump to

Keyboard shortcuts

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