ginger/lexer/lexer.go

342 lines
6.2 KiB
Go
Raw Normal View History

2016-07-07 02:46:49 +00:00
package lexer
import (
"bufio"
"bytes"
"errors"
2016-07-07 02:46:49 +00:00
"fmt"
"io"
2016-07-23 16:34:14 +00:00
"log"
2016-07-07 02:46:49 +00:00
"strings"
)
// TokenType indicates the type of a token
type TokenType string
// Different token types
const (
Identifier TokenType = "identifier"
Punctuation TokenType = "punctuation"
String TokenType = "string"
Err TokenType = "err"
EOF TokenType = "eof"
2016-07-07 02:46:49 +00:00
)
// Token is a single token which has been read in. All Tokens have a non-empty
// Val
type Token struct {
TokenType
Val string
Row, Col int
}
// Equal returns whether two tokens are of equal type and value
func (tok Token) Equal(tok2 Token) bool {
return tok.TokenType == tok2.TokenType && tok.Val == tok2.Val
}
// Err returns the error contained by the token, if any. Only returns non-nil if
2016-07-23 16:59:11 +00:00
// TokenType is Err or EOF
func (tok Token) Err() error {
if tok.TokenType == Err || tok.TokenType == EOF {
2016-07-23 16:59:11 +00:00
return fmt.Errorf("[line:%d col:%d] %s", tok.Row, tok.Col, tok.Val)
}
return nil
}
func (tok Token) String() string {
var typ string
switch tok.TokenType {
case Identifier:
typ = "ident"
case Punctuation:
typ = "punct"
case String:
typ = "str"
case Err, EOF:
typ = "err"
}
return fmt.Sprintf("%s(%q)", typ, tok.Val)
}
type lexerFn func(*Lexer) lexerFn
2016-07-07 02:46:49 +00:00
// Lexer is used to read in ginger tokens from a source. HasNext() must be
// called before every call to Next()
2016-07-07 02:46:49 +00:00
type Lexer struct {
in *bufio.Reader
out *bytes.Buffer
cur lexerFn
next []Token
row, col int
absRow, absCol int
}
// New returns a Lexer which will read tokens from the given source.
func New(r io.Reader) *Lexer {
return &Lexer{
in: bufio.NewReader(r),
out: new(bytes.Buffer),
cur: lex,
row: -1,
col: -1,
}
}
func (l *Lexer) emit(t TokenType) {
str := l.out.String()
if str == "" {
panic("cannot emit empty token")
}
l.out.Reset()
l.emitTok(Token{
2016-07-07 02:46:49 +00:00
TokenType: t,
Val: str,
Row: l.row,
Col: l.col,
})
}
func (l *Lexer) emitErr(err error) {
tok := Token{
TokenType: Err,
Val: err.Error(),
Row: l.absRow,
Col: l.absCol,
}
if err == io.EOF {
tok.TokenType = EOF
}
l.emitTok(tok)
}
func (l *Lexer) emitTok(tok Token) {
l.next = append(l.next, tok)
2016-07-07 02:46:49 +00:00
l.row = -1
l.col = -1
}
func (l *Lexer) readRune() (rune, error) {
2016-07-07 02:46:49 +00:00
r, _, err := l.in.ReadRune()
if err != nil {
return r, err
2016-07-07 02:46:49 +00:00
}
if r == '\n' {
l.absRow++
l.absCol = 0
} else {
l.absCol++
}
return r, err
2016-07-07 02:46:49 +00:00
}
func (l *Lexer) peekRune() (rune, error) {
r, _, err := l.in.ReadRune()
if err != nil {
return r, err
2016-07-07 02:46:49 +00:00
}
if err := l.in.UnreadRune(); err != nil {
return r, err
2016-07-07 02:46:49 +00:00
}
return r, nil
}
func (l *Lexer) readAndPeek() (rune, rune, error) {
r, err := l.readRune()
if err != nil {
return r, 0, err
}
n, err := l.peekRune()
return r, n, err
2016-07-07 02:46:49 +00:00
}
func (l *Lexer) bufferRune(r rune) {
l.out.WriteRune(r)
if l.row < 0 && l.col < 0 {
l.row, l.col = l.absRow, l.absCol
}
}
// HasNext returns true if Next should be called, and false if it should not be
// called and Err should be called instead. When HasNext returns false the Lexer
// is considered to be done
func (l *Lexer) HasNext() bool {
for {
if len(l.next) > 0 {
return true
} else if l.cur == nil {
2016-07-07 02:46:49 +00:00
return false
}
l.cur = l.cur(l)
2016-07-07 02:46:49 +00:00
}
}
// Next returns the next available token. HasNext must be called before every
// call to Next
func (l *Lexer) Next() Token {
t := l.next[0]
l.next = l.next[1:]
if len(l.next) == 0 {
l.next = nil
}
return t
}
2016-07-23 16:34:14 +00:00
////////////////////////////////////////////////////////////////////////////////
// the actual fsm
2016-07-07 02:46:49 +00:00
var whitespaceSet = " \n\r\t\v\f"
var punctuationSet = ",{}()<>|"
var identifierSepSet = whitespaceSet + punctuationSet
func lex(l *Lexer) lexerFn {
r, err := l.readRune()
if err != nil {
l.emitErr(err)
return nil
}
// handle comments first, cause we have to peek for those. We ignore errors,
// and assume that any error that would happen here will happen again the
// next read
2016-07-23 16:34:14 +00:00
if n, _ := l.peekRune(); r == '/' && n == '/' {
return lexLineComment
2016-07-23 16:34:14 +00:00
} else if r == '/' && n == '*' {
return lexBlockComment
}
return lexSingleRune(l, r)
}
func lexSingleRune(l *Lexer, r rune) lexerFn {
2016-07-07 02:46:49 +00:00
switch {
case strings.ContainsRune(whitespaceSet, r):
return lex
case strings.ContainsRune(punctuationSet, r):
l.bufferRune(r)
l.emit(Punctuation)
return lex
2016-07-07 02:46:49 +00:00
case r == '"' || r == '\'' || r == '`':
canEscape := r != '`'
return lexStrStart(l, r, makeLexStr(r, canEscape))
2016-07-07 02:46:49 +00:00
default:
l.bufferRune(r)
return lexIdentifier
2016-07-07 02:46:49 +00:00
}
}
func lexIdentifier(l *Lexer) lexerFn {
r, err := l.readRune()
if err != nil {
l.emit(Identifier)
l.emitErr(err)
return nil
}
2016-07-07 02:46:49 +00:00
if strings.ContainsRune(identifierSepSet, r) {
l.emit(Identifier)
return lexSingleRune(l, r)
2016-07-07 02:46:49 +00:00
}
l.bufferRune(r)
2016-07-07 02:46:49 +00:00
return lexIdentifier
}
func lexLineComment(l *Lexer) lexerFn {
r, err := l.readRune()
if err != nil {
l.emitErr(err)
return nil
}
2016-07-07 02:46:49 +00:00
if r == '\n' {
return lex
}
return lexLineComment
}
2016-07-23 16:34:14 +00:00
// assumes the starting / has been read already
func lexBlockComment(l *Lexer) lexerFn {
depth := 1
log.Printf("in block comment")
var recurse lexerFn
recurse = func(l *Lexer) lexerFn {
r, err := l.readRune()
if err != nil {
l.emitErr(err)
return nil
}
n, _ := l.peekRune()
if r == '/' && n == '*' {
depth++
} else if r == '*' && n == '/' {
depth--
}
if depth == 0 {
return lexSkipThen(lex)
}
return recurse
}
return recurse
}
2016-07-07 02:46:49 +00:00
func lexStrStart(lexer *Lexer, r rune, then lexerFn) lexerFn {
lexer.bufferRune(r)
return then
}
func makeLexStr(quoteC rune, canEscape bool) lexerFn {
var fn lexerFn
fn = func(l *Lexer) lexerFn {
r, n, err := l.readAndPeek()
if err != nil {
if err == io.EOF {
if r == quoteC {
l.bufferRune(r)
l.emit(String)
l.emitErr(err)
return nil
}
l.emitErr(errors.New("expected end of string, got end of file"))
return nil
}
}
2016-07-07 02:46:49 +00:00
if canEscape && r == '\\' && n == quoteC {
l.bufferRune(r)
l.bufferRune(n)
2016-07-07 02:46:49 +00:00
return lexSkipThen(fn)
}
l.bufferRune(r)
2016-07-07 02:46:49 +00:00
if r == quoteC {
l.emit(String)
2016-07-07 02:46:49 +00:00
return lex
}
return fn
}
return fn
}
func lexSkipThen(then lexerFn) lexerFn {
return func(l *Lexer) lexerFn {
if _, err := l.readRune(); err != nil {
l.emitErr(err)
return nil
}
2016-07-07 02:46:49 +00:00
return then
}
}