github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/syntaxerror.go (about)

     1  package runtime
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	"github.com/arnodel/golua/parsing"
     8  	"github.com/arnodel/golua/token"
     9  )
    10  
    11  // A SyntaxError is a lua syntax error.
    12  type SyntaxError struct {
    13  	File string
    14  	Err  parsing.Error
    15  }
    16  
    17  // NewSyntaxError returns a pointer to a SyntaxError for the error err in file.
    18  func NewSyntaxError(file string, err parsing.Error) *SyntaxError {
    19  	return &SyntaxError{
    20  		File: file,
    21  		Err:  err,
    22  	}
    23  }
    24  
    25  // Error implements the error interface.
    26  func (e *SyntaxError) Error() string {
    27  	return fmt.Sprintf("%s:%s", e.File, e.Err)
    28  }
    29  
    30  // IsUnexpectedEOF returns true if the error signals that EOF was encountered
    31  // when further tokens were required.
    32  func (e *SyntaxError) IsUnexpectedEOF() bool {
    33  	switch e.Err.Got.Type {
    34  	case token.EOF, token.UNFINISHED:
    35  		return true
    36  	default:
    37  		return false
    38  	}
    39  }
    40  
    41  func ErrorIsUnexpectedEOF(err error) bool {
    42  	snErr, ok := AsSyntaxError(err)
    43  	return ok && snErr.IsUnexpectedEOF()
    44  }
    45  
    46  func AsSyntaxError(err error) (snErr *SyntaxError, ok bool) {
    47  	ok = errors.As(err, &snErr)
    48  	return
    49  }