go-parsekit/tokenize2/api.go

375 lines
13 KiB
Go

package tokenize2
import (
"git.makaay.nl/mauricem/go-parsekit/read"
)
// API holds the internal state of a tokenizer run and provides an API that
// tokenize.Handler functions can use to:
//
// • read and accept runes from the input (NextRune, Accept)
//
// • fork the API for easy lookahead support (Fork, Merge, Reset, Dispose)
//
// • flush already read input data when not needed anymore (FlushInput)
//
// • retrieve the tokenizer Result struct (Result) to read or modify the results
//
// BASIC OPERATION:
//
// To retrieve the next rune from the API, call the NextRune() method.
//
// When the rune is to be accepted as input, call the method Accept(). The rune
// is then added to the result runes of the API and the read cursor is moved
// forward.
//
// By invoking NextRune() + Accept() multiple times, the result can be extended
// with as many runes as needed. Runes collected this way can later on be
// retrieved using the method Result().Runes().
//
// It is mandatory to call Accept() after retrieving a rune, before calling
// NextRune() again. Failing to do so will result in a panic.
//
// Next to adding runes to the result, it is also possible to modify the
// stored runes or to add lexical Tokens to the result. For all things
// concerning results, take a look at the Result struct, which
// can be accessed though the method Result().
//
// FORKING OPERATION FOR EASY LOOKEAHEAD SUPPORT:
//
// Sometimes, we must be able to perform a lookahead, which might either
// succeed or fail. In case of a failing lookahead, the state of the
// API must be brought back to the original state, so we can try
// a different route.
//
// The way in which this is supported, is by forking an API struct by
// calling method Fork(). This will return a forked child API, with
// empty result data, but using the same read cursor position as the
// forked parent.
//
// After forking, the same interface as described for BASIC OPERATION can be
// used to fill the results. When the lookahead was successful, then
// Merge() can be called on the forked child to append the child's results
// to the parent's results, and to move the read cursor position to that
// of the child.
//
// When the lookahead was unsuccessful, then the forked child API can
// disposed by calling Dispose() on the forked child. This is not mandatory.
// Garbage collection will take care of this automatically.
// The parent API was never modified, so it can safely be used after disposal
// as if the lookahead never happened.
//
// Opinionized note:
// Many tokenizers/parsers take a different approach on lookaheads by using
// peeks and by moving the read cursor position back and forth, or by putting
// read input back on the input stream. That often leads to code that is
// efficient, however, in my opinion, not very intuitive to read. It can also
// be tedious to get the cursor position back at the correct position, which
// can lead to hard to track bugs. I much prefer this forking method, since
// no bookkeeping has to be implemented when implementing a parser.
type API struct {
reader *read.Buffer // the input data reader
lastRune rune // the rune as retrieved by the last NextRune() calll
lastRuneErr error // the error for the last NextRune() call
runeRead bool // whether or not a rune was read using NextRune()
runes []rune // the rune stack
tokens []Token // the token stack
stackFrames []stackFrame // the stack frames, containing stack level-specific data
stackLevel int // the current stack level
stackFrame *stackFrame // the current stack frame
}
type stackFrame struct {
offset int // current rune offset relative to the Reader's sliding window
runeStart int
runeEnd int
tokenStart int
tokenEnd int
cursor Cursor
// TODO
err error // can be used by a Handler to report a specific issue with the input
}
const initialStackDepth = 10
const initialTokenDepth = 10
const initialRuneDepth = 10
// NewAPI initializes a new API struct, wrapped around the provided input.
// For an overview of allowed inputs, take a look at the documentation
// for parsekit.read.New().
func NewAPI(input interface{}) *API {
api := &API{
reader: read.New(input),
runes: make([]rune, 0, initialRuneDepth),
tokens: make([]Token, 0, initialTokenDepth),
stackFrames: make([]stackFrame, 1, initialStackDepth),
}
api.stackFrame = &api.stackFrames[0]
return api
}
// NextRune returns the rune at the current read offset.
//
// When an invalid UTF8 rune is encountered on the input, it is replaced with
// the utf.RuneError rune. It's up to the caller to handle this as an error
// when needed.
//
// After reading a rune it must be Accept()-ed to move the read cursor forward
// to the next rune. Doing so is mandatory. When doing a second call to NextRune()
// without explicitly accepting, this method will panic. You can see this as a
// built-in unit test, enforcing correct serialization of API method calls.
func (i *API) NextRune() (rune, error) {
if i.runeRead {
callerPanic("NextRune", "tokenize.API.{name}(): {name}() called at {caller} "+
"without a prior call to Accept()")
}
readRune, err := i.reader.RuneAt(i.stackFrame.offset)
i.lastRune = readRune
i.lastRuneErr = err
i.runeRead = true
return readRune, err
}
// Accept the last rune as read by NextRune() into the Result runes and move
// the cursor forward.
//
// It is not allowed to call Accept() when the previous call to NextRune()
// returned an error. Calling Accept() in such case will result in a panic.
func (i *API) Accept() {
if !i.runeRead {
callerPanic("Accept", "tokenize.API.{name}(): {name}() called at {caller} "+
"without first calling NextRune()")
} else if i.lastRuneErr != nil {
callerPanic("Accept", "tokenize.API.{name}(): {name}() called at {caller}, "+
"but the prior call to NextRune() failed")
}
i.runes = append(i.runes, i.lastRune)
i.stackFrame.runeEnd++
i.stackFrame.cursor.moveByRune(i.lastRune)
i.stackFrame.offset++
i.runeRead = false
}
// Fork forks off a child of the API struct. It will reuse the same
// read buffer and cursor position, but for the rest this is a fresh API.
//
// By forking an API, you can freely work with the forked child, without
// affecting the parent API. This is for example useful when you must perform
// some form of lookahead.
//
// When processing of the Handler was successful and you want to add the results
// to the parent API, you can call Merge() on the forked child.
// This will add the results to the results of the parent (runes, tokens).
// It also updates the read cursor position of the parent to that of the child.
//
// When the lookahead was unsuccessful, then the forked child API can
// disposed by calling Dispose() on the forked child. This is not mandatory.
// Garbage collection will take care of this automatically.
// The parent API was never modified, so it can safely be used after disposal
// as if the lookahead never happened.
func (i *API) Fork() int {
newStackLevel := i.stackLevel + 1
newStackSize := newStackLevel + 1
// Grow the stack frames capacity when needed.
if cap(i.stackFrames) < newStackSize {
newFrames := make([]stackFrame, newStackSize, newStackSize*2)
copy(newFrames, i.stackFrames)
i.stackFrames = newFrames
} else {
i.stackFrames = i.stackFrames[0:newStackSize]
}
parent := i.stackFrame
i.stackLevel++
i.stackFrame = &i.stackFrames[i.stackLevel]
*i.stackFrame = *parent
i.stackFrame.runeStart = parent.runeEnd
i.stackFrame.tokenStart = parent.tokenEnd
i.runeRead = false
return i.stackLevel
}
// Merge appends the results of a forked child API (runes, tokens) to the
// results of its parent. The read cursor of the parent is also updated
// to that of the forked child.
//
// After the merge operation, the child results are reset so it can immediately
// be reused for performing another match. This means that all Result data are
// cleared, but the read cursor position is kept at its current position.
// This allows a child to feed results in chunks to its parent.
//
// Once the child is no longer needed, it can be disposed of by using the
// method Dispose(), which will return the tokenizer to the parent.
func (i *API) Merge(stackLevel int) {
if stackLevel == 0 {
callerPanic("Merge", "tokenize.API.{name}(): {name}() called at {caller} "+
"on the top-level API stack level 0")
}
if stackLevel != i.stackLevel {
callerPanic("Merge", "tokenize.API.{name}(): {name}() called at {caller} "+
"on API stack level %d, but the current stack level is %d "+
"(forgot to Dispose() a forked child?)", stackLevel, i.stackLevel)
}
parent := &i.stackFrames[stackLevel-1]
if parent.runeEnd == i.stackFrame.runeStart {
// The end of the parent slice aligns with the start of the child slice.
// Because of this, to merge the parent slice can simply be expanded
// to include the child slice.
// parent : |----------|
// child: |------|
// After merge operation:
// parent: |-----------------|
// child: |---> continue reading from here
parent.runeEnd = i.stackFrame.runeEnd
i.stackFrame.runeStart = i.stackFrame.runeEnd
} else {
// The end of the parent slice does not align with the start of the
// child slice. The child slice has to be copied onto the end of
// the parent slice.
// parent : |----------|
// child: |------|
// After merge operation:
// parent: |-----------------|
// child: |---> continue reading from here
i.runes = append(i.runes[:parent.runeEnd], i.runes[i.stackFrame.runeStart:i.stackFrame.runeEnd]...)
parent.runeEnd = len(i.runes)
i.stackFrame.runeStart = parent.runeEnd
i.stackFrame.runeEnd = parent.runeEnd
}
// The same logic applies to tokens.
if parent.tokenEnd == i.stackFrame.tokenStart {
parent.tokenEnd = i.stackFrame.tokenEnd
i.stackFrame.tokenStart = i.stackFrame.tokenEnd
} else {
i.tokens = append(i.tokens[:parent.tokenEnd], i.tokens[i.stackFrame.tokenStart:i.stackFrame.tokenEnd]...)
parent.tokenEnd = len(i.tokens)
i.stackFrame.tokenStart = parent.tokenEnd
i.stackFrame.tokenEnd = parent.tokenEnd
}
parent.offset = i.stackFrame.offset
parent.cursor = i.stackFrame.cursor
i.stackFrame.err = nil
i.runeRead = false
}
func (i *API) Dispose(stackLevel int) {
if stackLevel == 0 {
callerPanic("Dispose", "tokenize.API.{name}(): {name}() called at {caller} "+
"on the top-level API stack level 0")
}
if stackLevel != i.stackLevel {
callerPanic("Dispose", "tokenize.API.{name}(): {name}() called at {caller} "+
"on API stack level %d, but the current stack level is %d "+
"(forgot to Dispose() a forked child?)", stackLevel, i.stackLevel)
}
i.runeRead = false
i.stackLevel = stackLevel - 1
i.stackFrames = i.stackFrames[:stackLevel]
i.stackFrame = &i.stackFrames[stackLevel-1]
i.runes = i.runes[0:i.stackFrame.runeEnd]
i.tokens = i.tokens[0:i.stackFrame.tokenEnd]
}
func (i *API) Reset() {
i.runeRead = false
i.stackFrame.runeStart = i.stackFrame.runeEnd
i.stackFrame.tokenStart = i.stackFrame.tokenEnd
i.stackFrame.err = nil
}
// FlushInput flushes processed input data from the read.Buffer.
// In this context 'processed' means all runes that were read using NextRune()
// and that were added to the results using Accept().
//
// Note:
// When writing your own TokenHandler, you normally won't have to call this
// method yourself. It is automatically called by parsekit when needed.
func (i *API) FlushInput() bool {
// result := &(i.state.stack[i.stackLevel])
if i.stackFrame.offset > 0 {
i.reader.Flush(i.stackFrame.offset)
i.stackFrame.offset = 0
return true
}
return false
}
func (i *API) String() string {
return string(i.Runes())
}
func (i *API) Runes() []rune {
return i.runes[i.stackFrame.runeStart:i.stackFrame.runeEnd]
}
func (i *API) Rune(offset int) rune {
return i.runes[i.stackFrame.runeStart+offset]
}
func (i *API) ClearRunes() {
i.runes = i.runes[:i.stackFrame.runeStart]
i.stackFrame.runeEnd = i.stackFrame.runeStart
}
func (i *API) SetRunes(runes ...rune) {
i.runes = append(i.runes[:i.stackFrame.runeStart], runes...)
i.stackFrame.runeEnd = i.stackFrame.runeStart + len(runes)
}
func (i *API) AddRunes(runes ...rune) {
i.runes = append(i.runes[:i.stackFrame.runeEnd], runes...)
i.stackFrame.runeEnd += len(runes)
}
func (i *API) AddString(s string) {
i.AddRunes([]rune(s)...)
}
func (i *API) SetString(s string) {
i.SetRunes([]rune(s)...)
}
func (i *API) Cursor() Cursor {
return i.stackFrame.cursor
}
func (i *API) Tokens() []Token {
return i.tokens[i.stackFrame.tokenStart:i.stackFrame.tokenEnd]
}
func (i *API) Token(offset int) Token {
return i.tokens[i.stackFrame.tokenStart+offset]
}
func (i *API) TokenValue(offset int) interface{} {
return i.tokens[i.stackFrame.tokenStart+offset].Value
}
func (i *API) ClearTokens() {
i.tokens = i.tokens[:i.stackFrame.tokenStart]
i.stackFrame.tokenEnd = i.stackFrame.tokenStart
}
func (i *API) SetTokens(tokens ...Token) {
i.tokens = append(i.tokens[:i.stackFrame.tokenStart], tokens...)
i.stackFrame.tokenEnd = i.stackFrame.tokenStart + len(tokens)
}
func (i *API) AddTokens(tokens ...Token) {
i.tokens = append(i.tokens[:i.stackFrame.tokenEnd], tokens...)
i.stackFrame.tokenEnd += len(tokens)
}