Documentation ¶
Overview ¶
This package provides a Lexer that functions similarly to Rob Pike's discussion about lexer design in this [talk](https://www.youtube.com/watch?v=HxaD_trXwRE).
Original implementation forked from https://github.com/bbuck/go-lexer.
You can define your token types by using the `lexer.TokenType` type (`int`) via
const ( StringToken lexer.TokenType = iota IntegerToken // etc... )
And then you define your own state functions (`lexer.StateFunc`) to handle analyzing the string.
func StringState(l *lexer.L) lexer.StateFunc { l.Next() // eat starting " l.Ignore() // drop current value while l.Peek() != '"' { l.Next() } l.Emit(StringToken) return SomeStateFunction }
Example (Lexer) ¶
b := bytes.NewBufferString("1 2 ") l := New(b, NumberState) l.ErrorHandler = func(e string) {} var tokens []Token l.Scan(func(tok Token) { tokens = append(tokens, tok) }) fmt.Printf("%#v", tokens)
Output: []lexer.Token{lexer.Token{Type:0, Value:"1"}}
Index ¶
- Constants
- func Not(t TokenType, f func(Token)) func(Token)
- type L
- func (l *L) Current() string
- func (l *L) Emit(t TokenType)
- func (l *L) Error(e string)
- func (l *L) Ignore()
- func (l *L) Next() rune
- func (l *L) NextToken() *Token
- func (l *L) NextTokens() []*Token
- func (l *L) Peek() rune
- func (l *L) ReadBytes() int
- func (l *L) Rewind()
- func (l *L) Scan(f func(t Token))
- func (l *L) Take(chars string)
- type StateFunc
- type Token
- type TokenType
Examples ¶
Constants ¶
const ( EOFRune rune = -1 EmptyToken TokenType = 0 )
Variables ¶
This section is empty.
Functions ¶
Types ¶
type L ¶
type L struct { Err error // tokens chan Token TokenHandler func(t Token) ErrorHandler func(e string) // contains filtered or unexported fields }
func (*L) Emit ¶
Emit will receive a token type and push a new token with the current analyzed value into the tokens channel.
func (*L) Ignore ¶
func (l *L) Ignore()
Ignore clears the rewind stack and then sets the current beginning position to the current position in the source which effectively ignores the section of the source being analyzed.
func (*L) Next ¶
Next pulls the next rune from the Lexer and returns it, moving the position forward in the source.
func (*L) NextTokens ¶
NextTokens Reads until at least one token is met, it returns nil a []*Token{nil} at EOF.
func (*L) Peek ¶
Peek performs a Next operation immediately followed by a Rewind returning the peeked rune.
func (*L) Rewind ¶
func (l *L) Rewind()
Rewind will take the last rune read (if any) and rewind back. Rewinds can occur more than once per call to Next but you can never rewind past the last point a token was emitted.