75 lines
2.4 KiB
Go
75 lines
2.4 KiB
Go
package parsekit
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// Emit passes a Parser item to the client, including the provided string.
|
|
func (p *P) Emit(t ItemType, s string) {
|
|
p.items <- Item{t, s}
|
|
p.buffer.reset()
|
|
}
|
|
|
|
// EmitLiteral passes a Parser item to the client, including the accumulated
|
|
// string buffer data as a literal string.
|
|
func (p *P) EmitLiteral(t ItemType) {
|
|
p.Emit(t, p.buffer.asLiteralString())
|
|
}
|
|
|
|
// EmitLiteralTrim passes a Parser item to the client, including the
|
|
// accumulated string buffer data as a literal string with whitespace
|
|
// trimmed from it.
|
|
func (p *P) EmitLiteralTrim(t ItemType) {
|
|
p.Emit(t, strings.TrimSpace(p.buffer.asLiteralString()))
|
|
}
|
|
|
|
// EmitInterpreted passes a Parser item to the client, including the
|
|
// accumulated string buffer data a Go doubled quoted interpreted string
|
|
// (handling escape codes like \n, \t, \uXXXX, etc.)
|
|
// This method might return an error, in case there is data in the
|
|
// string buffer that is not valid for string interpretation.
|
|
func (p *P) EmitInterpreted(t ItemType) error {
|
|
s, err := p.buffer.asInterpretedString()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
p.Emit(t, s)
|
|
return nil
|
|
}
|
|
|
|
// EmitError emits a Parser error item to the client.
|
|
func (p *P) EmitError(format string, args ...interface{}) {
|
|
message := fmt.Sprintf(format, args...)
|
|
p.Emit(ItemError, message)
|
|
}
|
|
|
|
// UnexpectedInput is used by a parser implementation to emit an
|
|
// error item that tells the client that an unexpected rune was
|
|
// encountered in the input.
|
|
// The parameter 'expected' is used to provide some context to the error.
|
|
func (p *P) UnexpectedInput(expected string) {
|
|
// next() takes care of error messages in cases where ok == false.
|
|
// Therefore, we only provide an error message for the ok case here.
|
|
r, _, ok := p.peek(0)
|
|
switch {
|
|
case ok:
|
|
p.EmitError("unexpected character %q (expected %s)", r, expected)
|
|
case r == EOF:
|
|
p.EmitError("unexpected end of file (expected %s)", expected)
|
|
case r == utf8.RuneError:
|
|
p.EmitError("invalid UTF8 character in input (expected %s)", expected)
|
|
default:
|
|
panic("Unhandled output from peek()")
|
|
}
|
|
}
|
|
|
|
// UnexpectedEndOfFile is used by a parser implementation to emit an
|
|
// error item that tells the client that more data was expected from
|
|
// the input.
|
|
// The parameter 'expected' is used to provide some context to the error.
|
|
func (p *P) UnexpectedEndOfFile(expected string) {
|
|
p.EmitError("Unexpected end of file (expected %s)", expected)
|
|
}
|